简单的生产者、消费者,一个数据缓冲区,一个或者多个生产者把数据放入缓冲区。一个或者多个消费者将数据从缓冲区取走。该缓冲区是一个数据共享,必须进行同步处理,如果缓冲区是满的,生产者将不能放数据,同理如果缓冲区是空的,消费者将不能取数据。
Storage.java
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class Storage {
private int maxSize;
private List<Date> storage;
public Storage() {
maxSize = 10;
storage = new LinkedList<Date>();
}
public synchronized void get() {
while (storage.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("get : %d: %s ", storage.size(),
((LinkedList<?>) storage).poll());
notifyAll();
}
public synchronized void put() {
while (storage.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.add(new Date());
System.out.printf("put : %d ", storage.size());
notifyAll();
}
}
Produce.java
public class Produce implements Runnable {
private Storage storage;
Produce(Storage s) {
this.storage = s;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.put();
}
}
}
Consumer.java
public class Consumer implements Runnable {
private Storage storage;
Consumer(Storage s) {
this.storage = s;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.get();
}
}
}
main.java
public static void main(String[] args) {
Storage s = new Storage();
Produce produce = new Produce(s);
Consumer consumer = new Consumer(s);
Thread thread1 = new Thread(produce);
Thread thread2 = new Thread(consumer);
thread1.start();
thread2.start();
}