生产者&消费者

59 阅读1分钟

事件存储器(临界资源)

package producer_consumer;

import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

public class EventStorage {
    private int maxSize;
    private Queue<Date> storage;

    public EventStorage() {
        maxSize = 10;
        storage = new LinkedList<>();
    }

    public synchronized void set(){
        while (storage.size()==maxSize){
            try {
                // 使用wait()方法后,当前线程将进入休眠状态,并与此同时释放当前线程正在执行的synchronized代码块以允许其他线程能够进入由同一个对象绑定的synchronized代码块。
                wait(); // 存储器满场景,当前线程进入等待状态,等待其他线程(消费者)唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.offer(new Date());
        System.out.printf("Set:%d ",storage.size());
        notify(); // 唤醒消费者线程
    }

    public synchronized void get(){
        while (storage.size()==0){
            try {
                wait(); // 存储器空场景,当前线程进入等待状态,等待其他线程(生产者)唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String element=storage.poll().toString();
        System.out.printf("Get: %d: %s\n",storage.size(),element);
        notify(); // 唤醒生产者线程
    }
}

生产者

package producer_consumer;

public class Producer implements Runnable {
    private EventStorage storage;

    public Producer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            storage.set();
        }
    }
}

消费者

package producer_consumer;

public class Consumer implements Runnable {
    private EventStorage storage;

    public Consumer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            storage.get();
        }
    }
}

Main测试类

package producer_consumer;

public class Main {
    public static void main(String[] args) {
        EventStorage storage=new EventStorage();
        Thread thread1=new Thread(new Producer(storage));
        Thread thread2=new Thread(new Consumer(storage));
        thread2.start();
        thread1.start();
    }
}