간단한 생산 소비 절차를 실현하다

5530 단어
package com.pcxm.blockqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class QueueTest {
    public static AtomicInteger atomicInteger = new AtomicInteger(0);
    public volatile static Boolean isRun = true;
    public volatile static Boolean isConsum = true;
    public static void main(String[] args) throws Exception {
        BlockingQueue que = new LinkedBlockingQueue<>();
        //      
        ExecutorService producerPool = Executors.newFixedThreadPool(5);
        //      
        ExecutorService consumerPool = Executors.newFixedThreadPool(5);
        producerPool.execute(new Runnable() {
            @Override
            public void run() {
                System.err.println("         !");
                while (isRun) {
                    System.out.println("      ...");
                    try {
                        int incrementAndGet = atomicInteger.incrementAndGet();
                        Thread.sleep(1000);
                        if(incrementAndGet > 10){
                            break;
                        }
                        System.out.println("   " + incrementAndGet + "      ");
                        que.put("  " + incrementAndGet);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });

        consumerPool.execute(new Runnable() {
            @Override
            public void run() {
                System.err.println("         ");
                while (isConsum) {
                    try {
                        String poll = que.poll(2, TimeUnit.SECONDS);
                        if(poll==null){
                           break;
                        }
                        System.err.println("    " + poll);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        producerPool.shutdown();
        consumerPool.shutdown();
    }
}

 
전재 대상:https://www.cnblogs.com/hetutu-5238/p/9084357.html

좋은 웹페이지 즐겨찾기