黑马程序员技术交流社区
标题:
多线程死锁(notifyAll())问题
[打印本页]
作者:
EDDY_Liang
时间:
2014-6-16 19:09
标题:
多线程死锁(notifyAll())问题
//需求:生产烤鸭,生产者生产一份,消费者消费一份,
//且生产者和消费者是多个。
class Resourse
{
String name;
int count=1;
boolean flag = false;
synchronized void producer()
{
while(this.flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"生产烤鸭"+".........."+this.count);
this.flag = true;
this.notifyAll();
}
synchronized void customer()
{
while(!this.flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+","+"xiaofei"+"..............................."+this.count);
this.flag = false;
this.count++;
this.notifyAll();
}
}
class ShengChan implements Runnable
{
Resourse r;
ShengChan(Resourse r)
{
this.r = r;
}
public void run()
{
r.producer();
}
}
class XiaoFei implements Runnable
{
Resourse r;
XiaoFei(Resourse r)
{
this.r = r;
}
public void run()
{
r.customer();
}
}
class Test
{
public static void main(String[] args)
{
Resourse r = new Resourse();
ShengChan a = new ShengChan(r);
XiaoFei b = new XiaoFei(r);
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
Thread t3 = new Thread(b);
Thread t4 = new Thread(b);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
复制代码
为什么我这个多线程的问题,用notifyAll();了还是死锁啊,试了N次都是每个线程运行了一下。。求大神解答,谢谢
作者:
月光海
时间:
2014-6-16 19:26
没有死锁好不好,你的程序已经结束了,因为你把每个线程只运行了一次,如果要多次运行,请把资源类里的方法中加上循环
作者:
、海
时间:
2014-6-16 19:59
本帖最后由 、海 于 2014-6-16 20:21 编辑
//需求:生产烤鸭,生产者生产一份,消费者消费一份,
//且生产者和消费者是多个。
class Resourse
{
String name;
int count=1;
boolean flag = false;
synchronized void producer()
{
作者:
、海
时间:
2014-6-16 20:13
本帖最后由 、海 于 2014-6-16 20:29 编辑
while(true){//
此处修改
if(flag) //
此处修改
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"生产烤鸭"+".........."+this.count);
} //
此处修改
this.flag = true;
this.notifyAll();
}
作者:
、海
时间:
2014-6-16 20:15
本帖最后由 、海 于 2014-6-16 20:29 编辑
synchronized void customer(){
while(true){//
此处修改
if(!this.flag)//
此处修改
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+","+"xiaofei"+"..............................."+this.count);
}//
此处修改
this.flag = false;
this.count++;
this.notifyAll(); }
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2