【多线程】--生产者消费者模式--Lock版本

时间:2023-03-09 03:04:36
【多线程】--生产者消费者模式--Lock版本

在JDK1.5发布后,提供了Synchronized的更优解决方案:Lock 和 Condition

我们使用这些新知识,来改进例子:【多线程】--生产者消费者模式--Synchronized版本

改进代码如下:

package com.shindo.java.thread;
import java.util.concurrent.locks.*;
/**
* Jdk 1.5中,提供了多线程升级解决办法
* 将同步Synchronized 替换为显示的Lock操作
* 将Object中的wait、notify、notifyAll替换为Condition对象
* 该对象通过Lock锁进行获取
* 一个锁Lock上可以有多个相关的Condition对象
*/
public class ProducerAndConsumerPatternBetter {
public static void main(String[] args){
Resource2 r = new Resource2();
new Thread(new Producer2(r)).start();
new Thread(new Consumer2(r)).start();
}
} /**
* 定义资源类,负责提供商品的生产方法和消费方法
*/
class Resource2 {
//定义商品变量
private String name;
//定义自增长计数器
private int count = 1;
//定义逻辑标志位
private boolean flag = false;
//通过多态的方法,生成Lock对象的实例
private Lock lock = new ReentrantLock();
//定义生产者的Condition对象
private Condition condition_pro = lock.newCondition();
//定义消费者的Condition对象
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 out()throws InterruptedException{
lock.lock();
try {
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"--##消费者##--"+this.name);
flag = false;
condition_pro.signal();
} finally{
lock.unlock();
}
}
} /**
* 定义产品生产类
*/
class Producer2 implements Runnable{
private Resource2 res;
Producer2(Resource2 res){
this.res = res;
}
public void run(){
while(true){
try {
res.set("商品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} //定义产品消费类
class Consumer2 implements Runnable{
private Resource2 res;
Consumer2(Resource2 res){
this.res = res;
}
public void run(){
while(true){
try {
res.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

代码执行结果如下图:

【多线程】--生产者消费者模式--Lock版本