import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemo3 {
public static void main(String[] args) {
Resource r=new Resource("鸡腿");
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(in);
Thread t3=new Thread(out);
Thread t4=new Thread(out);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Input implements Runnable
{
private Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set();
}
}
}
class Output implements Runnable
{
private Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.get();
}
}
}
class Resource
{
private String name;
private Lock lock=new ReentrantLock();
private Condition d1=lock.newCondition();
private Condition d2=lock.newCondition();
private boolean flag=false;
public void set()
{
lock.lock();
try
{
while(flag)
{try{d1.await();}catch(InterruptedException e){}}
System.out.println(Thread.currentThread().getName()+"商品***"+name);
flag=false;
d2.signalAll();
}finally
{lock.unlock();}
}
public void get()
{
lock.lock();
try
{
while(!flag)
{try{d1.await();}catch(InterruptedException e){}}
System.out.println(Thread.currentThread().getName()+"消费***"+name);
flag=true;
d1.signalAll();
}finally
{lock.unlock();}
}
public Resource(String name)
{
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
运行时只有线程1和2跑起来了,3和4不知道出啥问题了跑不起来,自己看着郁闷的要死 |