A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郁金香大公爵 中级黑马   /  2015-7-25 17:50  /  219 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//多生产多消费 1.5版高效率方式
/*class Rec{
private String name;
private int count = 1;
private boolean flag;
private Lock lock = new ReentrantLock();
private Condition Producer_con = lock.newCondition();
private 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()+"...producer..."+this.name);
     flag = true;
     Consumer_con.signalAll();
    }finally{
   lock.unlock();
   }
}
public void get(){
  lock.lock();
  try{
   while(! flag)
   try{Consumer_con.await();}catch(InterruptedException e){}
   System.out.println(Thread.currentThread().getName()+"..Consumer.."+this.name);
   flag = false;
   Producer_con.signalAll();
  }finally{
   lock.unlock();
  }
}
}
class Producer implements Runnable{
    private Rec r;
    Producer(Rec r){
     this.r =r;
    }
@Override
public void run() {
   while(true)
    r.set("Tiramisu");
}
}
class Consumer implements Runnable{
    private Rec r;
    Consumer(Rec r){
     this.r = r;
    }
@Override
public void run() {
   while(true)
  r.get();
}
}
class FinalizeDemo{
public static void main(String[] args){
  Rec r = new Rec();
  Producer p = new Producer(r);
  Consumer c = new Consumer(r);
  Thread t1 = new Thread(p);
  Thread t2 = new Thread(p);
  Thread t3 = new Thread(c);
  Thread t4 = new Thread(c);
  t1.start();
  t2.start();
  t3.start();
  t4.start();
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马