- /*
- 生产者和消费者的升级版
- java新特性
- 问题是:
- private Condition condition_in=lock.newCondition();
- private Condition condition_out=lock.newCondition();
- 上面两个Condition怎么知道是属于那个线程的呢?好像程序也没有标记那个Condition是属于生产者还是消费者的啊?
- 到底是怎么区分的呢兄弟?
- condition_in.await();等待的是生产者的线程
- condition_out.signal();唤醒消费者的线程
- condition_out.await();等待的是消费者的线程
- condition_in.await();唤醒生产者的线程
- */
- import java.util.concurrent.locks.*;
- class Res3
- {
- private String name;
- private String sex;
- private boolean flag=false;
- private Lock lock=new ReentrantLock();
- private Condition condition_in=lock.newCondition();
- private Condition condition_out=lock.newCondition();
- public void setRes(String name,String sex)throws InterruptedException
- {
- lock.lock();
- //这里写try{}finally{}是为了避免当发生异常的时候,保证可以线程释放锁
- try
- {
- while(flag)
- //让生产者wait
- condition_in.await();
- this.name=name;
- this.sex=sex;
- System.out.println(Thread.currentThread().getName()+"生产者"+name+"..."+sex);
- flag=true;
- //这里用notifyAll唤醒所有线程,避免唤醒的是本方线程,注意如果用notify,它唤醒的是进入线程
- 池中的第一个线程,有可能唤醒的是本方线程,造成所有的线程都在等待
- //叫醒消费者
- condition_out.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
- public void getRes()throws InterruptedException
- {
- lock.lock();
- try
- {
- //当flag为false时消费者就等待,否则就消费
- while(!flag)
- condition_out.await();
- System.out.println(Thread.currentThread().getName()+"消费者"+name+"-----"+sex);
- flag=false;
- condition_in.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
- }
- class Input3 implements Runnable
- {
- private Res3 r;
- Input3(Res3 r)
- {
- this.r=r;
- }
- public void run()
- {
- int x=0;
- while(true)
- {
- if(x==0)
- {
-
- try{r.setRes("mike","man");}catch(Exception e){}
- }
- try{r.setRes("丽丽","女");}catch(Exception e){}
- x=(x+1)%2;
- }
- }
- }
- class Output3 implements Runnable
- {
- private Res3 r;
- Output3(Res3 r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- try{r.getRes();}catch(Exception e){}
- }
- }
- class InputOutputDemo3
- {
- public static void main(String[] args)
- {
- Res3 r=new Res3();
- Input3 in=new Input3(r);
- Output3 out=new Output3(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();
- }
- }
复制代码 |