Regarding producers and consumer pattern in java with blocking queue approach

前端 未结 3 1543
小鲜肉
小鲜肉 2021-01-03 16:41

I was doing a research in producers and consumer design patterns with regards to threads in java, I recently explored in java 5 with the introduction With introduction of Bl

3条回答
  •  难免孤独
    2021-01-03 17:16

    If you want to know another way to do this try using an ExecutorService

    public static void main(String... args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 100; i++) {
            System.out.println("Produced: " + i);
    
            final int finalI = i;
            service.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Consumed: " + finalI);
                }
            });
        }
        service.shutdown();
    }
    

    With just 10 tasks the producer can be finished before the consumer starts. If you try 100 tasks you may find them interleaved.

提交回复
热议问题