java生产者消费者

public class ProviderConsumer {
    private static final int MAX_CAPACITY = 16;
    private static Lock lock = new ReentrantLock();
    private static Condition full = lock.newCondition();
    private static Condition empty = lock.newCondition();
    private static AtomicInteger integer = new AtomicInteger();
    private static Queue<Integer> queue = new LinkedBlockingQueue<>(MAX_CAPACITY);

    static class Provider implements Runnable {
        @Override
        public void run() {
            for (; ; ) {
                lock.lock();
                try {
                    while (queue.size() == MAX_CAPACITY) {
                        System.out.println(Thread.currentThread().getName());
                        System.out.println("full");
//                        lock.unlock();// 这儿解锁相当于阻塞
                        full.await();
                    }
                    int i = integer.incrementAndGet();
                    queue.add(i);
                    System.out.println("provided:" + i);
                    Thread.sleep(50L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    empty.signal();
                    lock.unlock();// 这儿解锁相当于让线程自己抢锁
                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            for (; ; ) {
                lock.lock();
                try {
                    while (queue.size() == 0) {
                        System.out.println(Thread.currentThread().getName());
                        System.out.println("empty");
//                        lock.unlock();// 这儿解锁相当于阻塞
                        empty.await();
                    }
                    int i = integer.getAndDecrement();
                    queue.remove(i);
                    System.out.println("consumed:" + i);
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    full.signal();
                    lock.unlock();// 这儿解锁相当于让线程自己抢锁
                }
            }
        }

    }

    public static void main(String[] args) {
        long alive = 60L;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(MAX_CAPACITY, 
        MAX_CAPACITY, alive, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

        Provider provider = new Provider();
        Consumer consumer = new Consumer();
        executor.execute(provider);
        executor.execute(consumer);
//        new Thread(provider).start();
//        new Thread(consumer).start();
    }

}

猜你喜欢

转载自blog.csdn.net/eahau/article/details/82078716