高并发-生产消费模型(阻塞队列)

class Producer implements Runnable {
    private final BlockingQueue queue;

    Producer(BlockingQueue q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
//                Thread.sleep(10);
                queue.put(produce());
//                System.out.println("已生产:" + (queue.size() - queue.remainingCapacity()));
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    String produce() {
        String msg = DateTime.now().toString();
//        System.out.println(msg);
        return msg;
    }
}

class Consumer implements Runnable {
    private final BlockingQueue queue;

    Consumer(BlockingQueue q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
                Thread.sleep(10);
                consume(queue.take());
                System.out.println("已消费:" + queue.remainingCapacity());
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    void consume(String x) {
//        System.err.println(x);
    }
}

class Setup {

    public static void main(String[] args) throws InterruptedException {

        BlockingQueue q = new ArrayBlockingQueue(1000);
        Producer p = new Producer(q);
        new Thread(p).start();

//        int size = 8;
//        ExecutorService pool = Executors.newFixedThreadPool(size);
//        for (int i = 0; i < size; i++) {
//            pool.submit(new Consumer(q));
//        }

//        pool.awaitTermination(5, TimeUnit.SECONDS);

        Consumer c1 = new Consumer(q);
//        Consumer c2 = new Consumer(q);
        new Thread(c1).start();

//        new Thread(c2).start();


    }
}

你可能感兴趣的:(高并发)