Java并发 | wait和notify实现生产者消费者
2019-08-08 本文已影响0人
icebreakeros
wait和notify实现生产者消费者
实例
数据对象
/**
* 数据对象
*/
public class Data {
private List<String> list = new ArrayList<>();
synchronized public void push(String data) {
try {
while (list.size() != 0) {
this.wait();
}
list.add(data);
this.notify();
System.out.println("push: " + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public String pop() {
String result = "";
try {
while (list.size() == 0) {
this.wait();
}
result = list.get(0);
list.remove(0);
this.notify();
System.out.println("pop: " + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
}
生产者
/**
* 生产者
*/
public class Producer implements Runnable {
private Data data;
public Producer(Data data) {
this.data = data;
}
public void service() {
data.push("random=" + Math.random());
}
@Override
public void run() {
while (true) {
service();
}
}
}
消费者
/**
* 消费者
*/
public class Consumer implements Runnable {
private Data data;
public Consumer(Data data) {
this.data = data;
}
public void service() {
System.out.println("pop: " + data.pop());
}
@Override
public void run() {
while (true) {
service();
}
}
}