Java生産者消費者condition実現

20092 ワード

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingQueue {
    public static final Queue<Apple> queue = new LinkedList<>();
    public static final Lock lock = new ReentrantLock();

    private static final Condition un_empty = lock.newCondition();
    private static final Condition un_full = lock.newCondition();
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(new Producer01(queue, un_empty, un_full, lock), i + "    ").start();
            new Thread(new Consumer01(queue, un_empty, un_full, lock), i + "    ").start();
        }


    }


}
class Apple{}
class Consumer01 implements Runnable{
    private Queue<Apple> queue;
    private Condition un_empty;
    private Condition un_full;
    private Lock lock;
    public Consumer01(Queue<Apple> queue, Condition condition, Condition condition1, Lock lock) {
        this.queue = queue;
        this.un_empty = condition;
        this.un_full = condition1;
        this.lock = lock;
    }

    @Override
    public void run() {
        while(true) {
            consume();
        }
    }

    private void consume() {
        try{
            lock.lock();
            while(queue.size() == 0) {
                un_empty.await();
            }
            queue.poll();
            System.out.println(Thread.currentThread().getName() + ":       ,  " + queue.size() + "   ");

            un_full.signal();
            Thread.sleep(200);
        }catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
class Producer01 implements Runnable{
    private Queue<Apple> queue;
    private Condition un_empty;
    private Condition un_full;
    private Lock lock;
    public Producer01(Queue<Apple> queue, Condition condition, Condition condition1, Lock lock) {
        this.queue = queue;
        this.un_empty = condition;
        this.un_full = condition1;
        this.lock = lock;
    }
    @Override
    public void run() {
        while (true) {
            produce();
        }
    }
    private void produce() {
        try{
            lock.lock();
            while(queue.size() == 100) {
                System.out.println("queue      ");
                un_full.await();
            }
            queue.offer(new Apple());
            System.out.println(Thread.currentThread().getName() + ":      ,  " +queue.size() + "   " );

            un_empty.signal();
            Thread.sleep(200);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}