黑马程序员技术交流社区
标题:
多线程
[打印本页]
作者:
郝勇
时间:
2013-4-12 18:56
标题:
多线程
本帖最后由 郝勇 于 2013-4-12 19:59 编辑
*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 19:33
一个小小的错误,刚刚还研究了半天。。太隐蔽了- -
在Mom方法中的if语句把所有的都括起来了,导致无法执行。。
改一下就行了。。
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();
}
复制代码
作者:
郝勇
时间:
2013-4-12 19:58
恩 多谢 大神!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2