• Как работать с потоками?

    angry_cellophane
    @angry_cellophane
    public class Main {
    
        public static final int WORKERS_COUNT = 3;
    
        private static class Worker implements Runnable {
    
            private final BlockingQueue<Integer> queue;
            private final int number;
    
            private Worker(BlockingQueue<Integer> queue, int number) {
                this.queue = queue;
                this.number = number;
            }
    
            @Override public void run() {
                try {
                    Integer i = queue.take();
                    System.out.println("number: "+number+", i ="+i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        public static void main(String[] args) {
            BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
            queue.add(1);
            queue.add(2);
            queue.add(3);
    
            ExecutorService pool = Executors.newFixedThreadPool(WORKERS_COUNT);
            for (int i = 0; i < WORKERS_COUNT; i++) {
                pool.execute(new Worker(queue, i));
            }
            pool.shutdown();
        }
    }
    Ответ написан
    Комментировать