????2??await()??signal()?????????????
package sort;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumer {
private LinkedList<Object> myList = new LinkedList<Object>();
private int MAX = 10;
private final Lock lock = new ReentrantLock();
private final Condition full = lock.newCondition();
private final Condition empty = lock.newCondition();
public ProducerConsumer() {
}
public void start() {
new Producer().start();
new Consumer().start();
}
public static void main(String[] args) throws Exception {
ProducerConsumer s2 = new ProducerConsumer();
s2.start();
}
class Producer extends Thread {
public void run() {
while (true) {
lock.lock();
try {
while (myList.size() == MAX) {
System.out.println("warning: it's full!");
full.await();
}
Object o = new Object();
if (myList.add(o)) {
System.out.println("Producer: " + o);
empty.signal();
}
} catch (InterruptedException ie) {
System.out.println("producer is interrupted!");
} finally {
lock.unlock();
}
}
}
}
class Consumer extends Thread {
public void run() {
while (true) {
lock.lock();
try {
while (myList.size() == 0) {
System.out.println("warning: it's empty!");
empty.await();
}
Object o = myList.removeLast();
System.out.println("Consumer: " + o);
full.signal();
} catch (InterruptedException ie) {
System.out.println("consumer is interrupted!");
} finally {
lock.unlock();
}
}
}
}
}
????3?????????е???
import java.util.concurrent.*;
public class ProducerConsumer {
// ???????????????
private LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(10);
public ProducerConsumer() {
}
public void start() {
new Producer().start();
new Consumer().start();
}
public static void main(String[] args) throws Exception {
ProducerConsumer s3 = new ProducerConsumer();
s3.start();
}
class Producer extends Thread {
public void run() {
while (true) {
try {
Object o = new Object();
// ??????????
queue.put(o);
System.out.println("Producer: " + o);
} catch (InterruptedException e) {
System.out.println("producer is interrupted!");
}
// }
}
}
}
class Consumer extends Thread {
public void run() {
while (true) {
try {
// ??????????
Object o = queue.take();
System.out.println("Consumer: " + o);
} catch (InterruptedException e) {
System.out.println("producer is interrupted!");
}
// }
}
}
}
}
????????
???????????????£??????????????????????????????????????????????????????????洢?????????????????????LinkedBlockingQueue???????