用五种方式来实现生产者消费者模型
- Object.wait/notify
- Lock/Condition
- BlockingQueue
- Semaphore
- Exchanger
方式一:synchronized、wait和notify
创建一个资源类Resource:
public class Resource {
//当前资源量
int num = 0;
//资源池中允许放的资源数目
int size = 10;
//向资源池中取走资源
int i = 0;
public synchronized void remove(){
if (num>0){
num–;
System.out.println(“消费者”+Thread.currentThread().getName()+“减去一个随机数”+i+“当前线程池有”+num+“个”);
notifyAll();//通知生产者生产资源
}else{
try {
//如果没有资源,则消费者进入等待状态
wait();
System.out.println(“消费者”+Thread.currentThread().getName()+“线程进入等待”);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
//向资源池中添加资源
public synchronized void add(){
if(num<size){
num++;
i = new Random().nextInt();
System.out.println(Thread.currentThread().getName()+“加个随机数”+i+“当前资源池还剩”+num+“个”);
//通知等待的消费者
notifyAll();
}else{
//如果有10个随机数
try {
wait();//生产者进入等待状态,并释放锁
System.out.println(Thread.currentThread().getName()+“线程进入等待”);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
实现:
public class ProducerConsumer1 {
public static void main(String[] args) throws InterruptedException {
Resource resource = new Resource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);
producer.start();
consumer.start();
producer.join();
consumer.join();
}
//生产者线程
public static class Producer extends Thread {
private Resource resource;
public Producer(Resource resource){
this.resource=resource;
}
@Override
public void run() {
int i = 0;
int j = 10;
while (i<j){
i++;
try {
//休眠1000毫秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.add();
}
}
}
//消费者线程
public static class Consumer extends Thread {
private Resource resource;
public Consumer(Resource resource){
this.resource = resource;
}
@Override
p