import java.util.concurrent.locks.*;
//实现生产消费
/*
wait()-----await()
notify()-----signal()
notifyAll()-----signalAll()
Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,
以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。
其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
*/
class Recsource2{
private String name;
private int count=1;
private boolean flag;
Lock lock = new ReentrantLock();
private Condition condition_pro =lock.newCondition();
private Condition condition_con =lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();//获取锁
try {
while(flag)
condition_pro.await();
this.name = name+"--"+(count++);
System.out.println(Thread.currentThread().getName()+".....生产者........"+this.name);
flag =true;
condition_con.signal();//唤醒对方
}finally{
lock.unlock();//释放锁
}
}
public void get() throws InterruptedException{
lock.lock();
try {
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+".....消费者"+name);
flag = false ;
condition_pro.signal();
}finally{
lock.unlock();
}
}
}
class Producer2 implements Runnable{
private Recsource2 res;
Producer2(Recsource2 res){
this.res = res;
}
public void run(){
while(true){
try {
res.set("商品");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer2 implements Runnable{
private Recsource2 res;
Consumer2(Recsource2 res){
this.res = res;
}
public void run(){
while(true){
try {
res.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ProducerConsumerDemo2 {
public static void main(String...args){
Recsource2 r = new Recsource2();
Producer2 p = new Producer2(r);
Consumer2 c = new Consumer2(r);
Thread t1 = new Thread(p,"生 产者1..");
Thread t5 = new Thread(p,"生产者2....");
Thread t2 = new Thread(c,"消费者1..");
Thread t3 = new Thread(p,"生产者3......");
Thread t4 = new Thread(c,"消费者2....");
t1.start();
t5.start();
t2.start();
t3.start();
t4.start();
}
}
|
|