Java多執行緒學習筆記(九) 生產者/消費者模式實現
阿新 • • 發佈:2018-12-20
1. 一個生產者和一個消費者:操作值
1.1 公共值
public class ValueObject {
public static String value = "";
}
1.2 生產者
public class Producer {
private String lock;
public Producer(String lock){
super();
this.lock = lock;
}
public void setValue(){
try{
synchronized (lock){
//如果公共值還沒有被消費,則當前執行緒等待
if (!ValueObject.value.equalsIgnoreCase("")){
lock.wait();
}else {
String value = System.currentTimeMillis() + "_" + System.nanoTime();
System.out.println("set value is " + value);
//生產者給公共值賦值
ValueObject.value = value;
}
//通知消費者可以消費了
lock.notify();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
注意: 執行到lock.wait()這句,wait()立即釋放鎖。
1.3 消費者
public class Consumer {
private String lock;
public Consumer(String lock){
super();
this.lock = lock;
}
public void getValue(){
try{
synchronized (lock){
if (ValueObject.value.equals("")){
lock.wait();
}
System.out.println("get value is " + ValueObject.value);
ValueObject.value = "";
lock.notify();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
1.4 生產者執行緒
public class ThreadP extends Thread {
private Producer producer;
public ThreadP(Producer producer){
super();
this.producer = producer;
}
@Override
public void run(){
while (true){
producer.setValue();
}
}
}
1.5 消費者執行緒
public class ThreadC extends Thread {
private Consumer consumer;
public ThreadC(Consumer consumer){
super();
this.consumer = consumer;
}
@Override
public void run(){
while (true){
consumer.getValue();
}
}
}
1.6 Test
public class Test {
public static void main(String[] args) {
String lock = new String("");
Producer producer = new Producer(lock);
ThreadP threadP = new ThreadP(producer);
Consumer consumer = new Consumer(lock);
ThreadC threadC = new ThreadC(consumer);
threadP.start();
threadC.start();
}
}
1.7 執行結果
...
set value is 1541748157877_7058115684144
get value is 1541748157877_7058115684144
set value is 1541748157877_7058115845581
get value is 1541748157877_7058115845581
set value is 1541748157877_7058115937711
get value is 1541748157877_7058115937711
set value is 1541748157877_7058116052944
get value is 1541748157877_7058116052944
...
set和get是交替出現的