import java.util.concurrent.locks.*; class Do9 { public static void main(String[] args) { Resource r=new Resource(); Shengchan sc=new Shengchan(r); Xiaoshou xs=new Xiaoshou(r); Thread th1=new Thread(sc); Thread th2=new Thread(sc); Thread th3=new Thread(xs); Thread th4=new Thread(xs); th1.start(); th2.start(); th3.start(); th4.start(); } } class Resource { private String name; private int count=1; private boolean flag=false; //创建一个锁对像 Lock lock=new ReentrantLock(); //通过已经有的锁获取该锁上的监视器对象 Condition shengchan_con=lock.newCondition();//创建生产者对象 Condition xiaofei_con=lock.newCondition();//创建消费者对象 public void set(String name) { lock.lock(); try { while(flag) try{shengchan_con.await();}catch(InterruptedException e){} this.name=name+count; count++; System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name); flag=true; xiaofei_con.signal(); } finally{ lock.unlock(); } } public synchronized void out() { lock.lock(); try { while(!flag) try{xiaofei_con.await();}catch(InterruptedException e){} System.out.println(Thread.currentThread().getName()+"..消费者........"+this.name); flag=false; shengchan_con.signal(); } finally{ lock.unlock(); } } } class Shengchan implements Runnable { private Resource r; Shengchan(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.set("烤鸭"); } } } class Xiaoshou implements Runnable { private Resource r; Xiaoshou(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.out(); } } }
时间: 2024-10-13 12:59:51