synchronized版本:
代码如下:
import java.util.LinkedList;
import java.util.Queue;
/**
* @author herman
*
*/
public class ProducerAndConsumer2 {
private final int max = 5;
private Queue<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) {
ProducerAndConsumer2 threadDemo2 = new ProducerAndConsumer2();
Thread th1 = threadDemo2.new Producer();
Thread th2 = threadDemo2.new Consumer();
th1.start();
th2.start();
}
class Producer extends Thread {
@Override
public void run() {
producer();
}
public synchronized void producer() {
while (true) {
synchronized (queue) {
if (queue.size() >= max) {
System.out.println("满了");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(1);
queue.notify();
System.out.println("+1, size是:" + queue.size());
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Consumer extends Thread {
@Override
public void run() {
consumer();
}
public synchronized void consumer() {
while (true) {
synchronized (queue) {
if (queue.size() == 0) {
System.out.println("空了");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
queue.notify();
System.out.println("-1, size是:" + queue.size());
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}