在同步代码块中使用条件(Using condition in synchronized code)
在并发编程中,生产者-消费者(producer-consumer)是一个经典的问题;一个数据缓冲区,一个或多个生产者向这个缓冲区写数据,一个或多个消费者从这个缓冲区中读数据,缓冲区作为线程共享资源,需要采用同步机制控制,比如使用synchronized关键字,但是我们还需要更多的限制条件,比如当缓冲区满时就不能在写入数据,当缓冲区空时就不能在读取数据;
对于这种情况,Javaz提供了wait() , notify()和notifyAll() 方法,这几个方法都是Object对象的方法;一个线程只能在synchronized代码块中调用wait()方法,如果在synchronized代码块之外调用wait()方法,JVM将会抛出一个IllegalMonitorStateException异常;当一个线程调用wait()方法时,这个线程将会被休眠(sleep)并且释放对之前锁定的对象中的同步代码块,此时其它线程将有机会执行这个对象的同步代码块;当要唤醒这个线城时,可以调用被锁定对象的notify()或notifyAll()方法;
下面的实例中将会展示这几个方法是如何使用的;
动手实现
1. 创建一个EventStorage类
public class EventStorage {
private int maxSize;
private LinkedList<Date> storage;
public EventStorage(){
maxSize=10;
storage = new LinkedList<>();
}
public synchronized void set() {
while (storage.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.offer(new Date());
System.out.printf("Set:%d\n",storage.size());
notifyAll();
}
public synchronized void get() {
while (storage.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("Get:%d: %s\n", storage.size(), storage.poll());
notifyAll();
}
}
2.分别创建生产者和消费者
public class Consumer implements Runnable {
private EventStorage eventStorage;
public Consumer(EventStorage eventStorage) {
this.eventStorage = eventStorage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
eventStorage.get();
}
}
}
public class Producer implements Runnable {
private EventStorage eventStorage;
public Producer(EventStorage eventStorage) {
this.eventStorage = eventStorage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
eventStorage.set();
}
}
}
3.Main
public class Main {
public static void main(String[] args) {
EventStorage storage=new EventStorage();
Producer producer=new Producer(storage);
Thread thread1=new Thread(producer);
Consumer consumer=new Consumer(storage);
Thread thread2=new Thread(consumer);
thread2.start();
thread1.start();
}
}
要点
观察运行结果,会发现eventstorage 至多会有10个事件