生产者消费者是最简单的java多线程例子之一,由生产者生产出东西,然后消费者消费,分别有两个线程调用生产者和消费者。
public class App {
public static void main(String[] args) {
final Processor processor=new Processor();
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
try {
processor.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
try {
processor.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
/**
* Created by gmy on 2017/10/14.
*/
public class Processor {
private LinkedList<Integer> list=new LinkedList<>();
private final int LIMIT=10;
private final Object lock=new Object();
public void produce() throws InterruptedException{
int value=0;
while(true){
synchronized (lock){
while(list.size()==LIMIT){
lock.wait();//如果list等于限制,则等待
}
list.add(value);
System.out.println("生产者新增了"+value+" 队列长度为"+list.size());
value++;
Thread.sleep(1000);
lock.notify();
}
}
}
public void consume() throws InterruptedException{
Random random=new Random();
while(true) {
synchronized (lock) {
while (list.size() == 0) {
lock.wait();//如果list等于限制,则等待
}
int value = list.removeFirst();
System.out.println("消费者从队列里取了" + value);
System.out.println("现在队列大小为" + list.size());
lock.notify();
}
Thread.sleep(random.nextInt(1000));
}
}
}