最简单的java生产者消费者示例
写了一个最简单的生产者消费者示例。一个线程向List中加入字符串,比如s0、s1、s2 … ,另外一个线程读取列表中第一个字符串,然后删除,相当于消费了。
虽然简单,但是基本上可以演示线程同步的主要功能,即对管程(monitor)的操作。学过操作系统都应该知道信号量和原语,用于对互斥的线程资源的调用。管程提供更高级的功能,编写起来更容易。
java使用了管程的概念,每个Object对象,都有一个内置的管程(monitor),因此可以通过wait/notify/synchronized机制产生对资源的互斥使用。因为java是单根的,因此可以说所有类对象都包含管程。
示例代码见:
这里先创建了消费者线程,它读取List,因为是空的,所以在List管程上wait,直到有线程调用List管程的notify或者notifyAll方法通知它,它才能被唤醒。wait的时候,会释放对管程的锁。
notify和notifyAll的区别是,前者通知一个wait线程,后者通知所有wait线程。
消费者:
class Consumer implements Runnable {
private List<String> contents;
public Consumer(List<String> contents) {
this.contents = contents;
}@Override
public void run() {
while (true) {
synchronized (contents) {
if (contents.isEmpty()) {
try {
contents.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println(contents.remove(0));
}
}
}
}
}
生产者:
class Producer implements Runnable {
private List<String> contents;
private int count;
public Producer(List<String> contents) {
this.contents = contents;
}@Override
public void run() {
while (true) {
synchronized (contents) {
this.contents.add("s" + (count++));
this.contents.notify();
}
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
这篇文章上的评论的 RSS feed TrackBack URI