import java.util.concurrent.locks.*;
public class ProducerConsumerDemo2
{
public static void main(String[] args)
{
//创建四个线程,并启动,两个生产者,两个消费者
Resource1 r = new Resource1();
Producer1 pro = new Producer1(r);
Consumer1 con = new Consumer1(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
public void set(String name)throws InterruptedException
{
lock.lock(); //获取锁
try
{
while(flag)
condition_pro.await(); //生产等待
this.name = name +"--"+count++;
System.out.println(Thread.currentThread().getName()+"-------生产者-------"+this.name);
flag = true;
condition_con.signal(); //唤醒对方的锁
}
finally
{
lock.unlock(); //释放锁
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_con.await();//消费等待
System.out.println(Thread.currentThread().getName()+"+++消费者+++"+this.name);
flag = false;
condition_pro.signal();//唤醒对方的锁
}
finally
{
lock.unlock();//释放锁
}
}
}
//下面的两段代码是生产者和消费者
class Producer1 implements Runnable
{
private Resource1 res;
Producer1 (Resource1 res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch (InterruptedException e)
{
}
}
}
}
class Consumer1 implements Runnable
{
private Resource1 res;
Consumer1 (Resource1 res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch (InterruptedException e)
{
}
}
}
}
没有发现代码错误,但运行时出现了死锁,why?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |