黑马程序员技术交流社区
标题:
多线程 买盐
[打印本页]
作者:
郝勇
时间:
2013-4-12 18:58
标题:
多线程 买盐
本帖最后由 郝勇 于 2013-4-13 04:19 编辑
public class Test10 {
public static void main(String[] args)
{
Salt s = new Salt();
new Thread(new Mom(s)).start();
new Thread(new Son(s)).start();
}
}
class Salt{
boolean flag = false;
}
class Mom implements Runnable
{
private Salt s;
Mom(Salt s)
{
this.s = s;
}
public void run()
{
while(true){
synchronized(s){
if(s.flag){
try{s.wait(1000);}
catch(Exception e){}
System.out.println("妈妈说:没盐了,儿子,买盐去!没法做饭了");
s.flag = true;
s.notify();
}
}
}
}
}
class Son implements Runnable{
private Salt s;
Son(Salt s)
{
this.s = s;
}
public void run()
{
while(true){
synchronized(s){
if(!s.flag)
try{s.wait();}catch(Exception e){}
System.out.println("好的,马上去买盐!!!");
s.flag = false;
s.notify();
}
}
}
}
复制代码
作者:
何俊森
时间:
2013-4-12 21:59
public class Cooking {
public static void main(String[] args) {
new Thread(new Mother()).start();
}
}
class Salt {
boolean flag = false;
}
class Mother implements Runnable {
public void run() {
System.out.println("开始做饭了");
System.out.println("妈妈说:\"没盐了,儿子,买盐去!\"");
Thread son = new Thread(new Son());
son.start();
try {
son.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("盐买回来,妈妈继续做饭。");
}
}
class Son implements Runnable {
public void run() {
System.out.println("儿子:\"好的,马上去买盐!\"");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
复制代码
没有太明白楼主的代码,private Salt s, s.notify();什么意思。买盐的问题可以参考一下以上代码。
作者:
刘林虎
时间:
2013-4-12 22:03
/**
* 模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐(假设买盐需要3分钟),只有盐买回来之后,妈妈才能继续做饭的过程。
*
*
*/
public class Test10 {
public static void main(String[] args) {
// 定义做饭的对象
final Cook c = new Cook();
// 定义一个妈妈做饭的线程,并启动
new Thread(new Runnable() {
public void run() {
while (true) {
c.makeCook();
}
}
}).start();
// 定义一个儿子买盐的线程,并启动
new Thread(new Runnable() {
public void run() {
while (true) {
c.buySalt();
}
}
}).start();
}
}
/**
* 因为妈妈儿子需要用到相同的锁对象,和相同的是否能做饭的标示对戏那个,所以把他们封装在一个类中的两个方法中。
*/
class Cook {
// 是否能做饭的标识
private boolean canCook = false;
/**
* 妈妈做饭的方法
*/
public synchronized void makeCook() {
// 如果没有盐,就等待3分钟,唤醒儿子去买盐。
if (!canCook) {
System.out.println("没有盐,不能做饭...");
System.out.println("等待买盐....");
try {
this.notify();
Thread.sleep(1000 * 3 * 60);
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 能做饭了。做完之后,把变量设置回去。
System.out.println("妈妈正在做饭。。。");
canCook = false;
}
/**
* 儿子买盐的方法
*/
public synchronized void buySalt() {
// 如果能做饭,儿子就休息
if (canCook) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有盐,儿子去买盐并唤醒妈妈,把能做饭设置true
System.out.println("儿子去买盐了,");
canCook = true;
this.notify();
}
}
复制代码
作者:
郝勇
时间:
2013-4-13 04:18
已经解决了,发一样的帖子是为了让更多的人看到给帮忙解决,这个是我自己粗心,多了一对{};已经改过来了,多谢下面两位,我会参考你们的编程思路的!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2