晨枫112358 2016-08-22 06:41 采纳率: 0%
浏览 833

java多线程初级死锁问题

import java.util.concurrent.locks.*;
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
//创建一个锁对象
Lock lock=new ReentrantLock();
Condition producer_con=lock.newCondition();
Condition consumer_con=lock.newCondition();
public void set(String name)
{ lock.lock();
try{

while(flag)
{try
{producer_con.await();}
catch(InterruptedException e){}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"。。。生产者。。。"+this.name);
flag=true;
consumer_con.signal();
}
finally{lock.unlock();}
}
public void show()
{ lock.lock();
try{

while(!flag)
try
{consumer_con.await();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"。。。消费者。。。"+this.name);
flag=false;
producer_con.signal();
}
finally{lock.unlock();}
}
}
class Producer implements Runnable
{private Resource r;
public Producer(Resource r)
{
this.r=r;
// TODO Auto-generated constructor stub
}
public void run()
{
r.set("烤鸭");
}
}
class Consumer implements Runnable
{private Resource r;
Consumer(Resource r)
{
this.r=r;
// TODO Auto-generated constructor stub
}
public void run()
{
r.show();
}
}
public class ProducerCustomer {
public static void main(String[]args)
{
Resource r=new Resource();
Producer p1=new Producer(r);
Producer p2=new Producer(r);
Consumer c1=new Consumer(r);
Consumer c2=new Consumer(r);
Thread t1=new Thread(p1);
Thread t2=new Thread(p2);
Thread t3=new Thread(c1);
Thread t4=new Thread(c2);
t1.start();
t2.start();
t3.start();
t4.start();

}
}

打印结果:
Thread-0。。。生产者。。。烤鸭1
Thread-2。。。消费者。。。烤鸭1
Thread-1。。。生产者。。。烤鸭2
Thread-3。。。消费者。。。烤鸭2

然后就没了。。。。请问是死锁了吗?怎么解决

  • 写回答

2条回答 默认 最新

  • 小黄人的banana 2016-08-25 02:30
    关注

    signAll()试试

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog