Escriba una cola de bloqueo de consumidores de productor a mano.

class MyResorces {
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingDeque = null;

    //构造器注入
    public MyResorces(BlockingQueue<String> blockingDeque) {
        this.blockingDeque = blockingDeque;
        System.out.println(blockingDeque.getClass().getName());
    }

    public void myProvider() throws InterruptedException {
        String data = null;
        boolean retValue;
        while (FLAG) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingDeque.offer(data, 2L, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t 生产者生产了" + data);
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 生产者生产失败了");
            }
            //TimeUnit.SECONDS.sleep(1);
        }
        System.out.println("关门了");
    }

    public void myConsumer() throws InterruptedException {
        String resutl = null;
        while (FLAG) {
            resutl = blockingDeque.poll(2L,TimeUnit.SECONDS);
            if (resutl == null || resutl.equals("")) {
                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "\t 超过了俩秒没消费 把标记改为False告诉生产者别生产了");
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费者消费了" +resutl);

        }

    }

    public void stop() {
        FLAG = false;
    }
}

public class ProCsu_BlockQueueDemo {
    public static void main(String[] args) {
        MyResorces myResorces = new MyResorces(new ArrayBlockingQueue<>(10));

        new Thread(() -> {
            try {
                myResorces.myProvider();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                myResorces.myConsumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myResorces.stop();
    }
}

Supongo que te gusta

Origin blog.csdn.net/qq_36905956/article/details/105881164
Recomendado
Clasificación