之前的代码是唤醒所有的线程,影响了效率,这里对该问题实现优化,具体的细节在代码中与之前的博客比较吧
//使用jdk1.5多线程的实现方式解决一次唤醒所有线程性能低的问题
//描述产品
import java.util.concurrent.locks.*;
class Product{
private String name;
private int count;
private boolean flag;
//1:创建一把锁
private Lock lock = new ReentrantLock();//父类引用指向子类对象,多态
//得到和锁绑定的Condition对象,控制生产线程的唤醒和等待
private Condition pro = lock.newCondition();
//得到和锁绑定的Condition对象,控制消费线程的唤醒和等待
private Condition con = lock.newCondition();
//生产产品的功能
public void produce(String name){
lock.lock();//获取锁
try{
//if(flag){//把if改为while
while(flag){
//IllegalMonitorStateException
try{pro.await();}catch(InterruptedException e){e.printStackTrace();}
}
this.name = name+"..."+count;
System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);
count++;
flag = true;
//唤醒消费线程,不再像之前,唤醒所有线程
con.signal();
}
finally{
lock.unlock();//释放锁
}
}
//消费产品的功能
public void consume(){
lock.lock();
try{
while(!flag){
try{con.await();}catch(InterruptedException e){e.printStackTrace();}
}
System.out.println(Thread.currentThread().getName()+"...消费了..."+this.name);
flag = false;
//唤醒生产线程,不再像之前,唤醒所有线程
pro.signal();
}
finally{
lock.unlock();
}
}
}
//生产任务
class Producer implements Runnable{
private Product pro;
public Producer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.produce("笔记本");
}
}
}
//消费任务
class Consumer implements Runnable{
private Product pro;
public Consumer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.consume();
}
}
}
class test{
public static void main(String[] args){
Product pro = new Product();
Producer producer = new Producer(pro);
Consumer consumer = new Consumer(pro);
Thread t0 = new Thread(producer);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
Thread t3 = new Thread(consumer);
t0.start();
t1.start();
t2.start();
t3.start();
}
}