//多生产多消费 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();
}
} |
|