通过synchronized、wait、notify实现
package cn.tedu.concurrent;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class ConsumerAndProducer {
private static LinkedList<Object> queue = new LinkedList<>();
private static int count = 0;
private static final int Max_SIZE = 10;
public static void main(String[] args) {
Producer p = new Producer();
Consumer c = new Consumer();
p.start();
c.start();
}
static class Producer extends Thread {
@Override
public void run() {
while (true){
synchronized (queue){
while (queue.size()==Max_SIZE){
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(count);
System.out.println("Producer...:"+count++);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.notifyAll();
}
}
}
}
static class Consumer extends Thread{
@Override
public void run() {
while (true){
synchronized (queue){
while (queue.size()==0){
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object e = queue.removeFirst();
System.out.println("消费。。:"+e.toString());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException s) {
s.printStackTrace();
}
queue.notifyAll();
}
}
}
}
}