zoukankan      html  css  js  c++  java
  • 简单生产消费模型

    import java.util.Queue;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.LinkedBlockingQueue;
    
    public class Application {
        final static int TASKCOUNT = 20;
    
        public static void main(String args[]) {
            CountDownLatch locked = new CountDownLatch(TASKCOUNT);
            Queue<Integer> queue = new LinkedBlockingQueue<>(TASKCOUNT);
            Producer producer = new Producer(locked, queue, TASKCOUNT);
            Consumer comsumer = new Consumer(locked, queue);
            new Thread(producer).start();
            new Thread(comsumer).start();
            new Thread(comsumer).start();
            System.out.println("主线程结束");
        }
    }
    
    class Producer implements Runnable {
    
        CountDownLatch locked;
        Queue<Integer> queue;
        int count;
    
        public Producer(CountDownLatch locked, Queue<Integer> queue, int count) {
            this.locked = locked;
            this.queue = queue;
            this.count = count;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                this.queue.add(i);
                this.locked.countDown();
            }
            System.out.println(String.format("生产线程 %s 结束",Thread.currentThread().getId()));
        }
    }
    
    class Consumer implements Runnable {
    
        CountDownLatch locked;
        Queue<Integer> queue;
    
        public Consumer(CountDownLatch locked, Queue<Integer> queue) {
            this.locked = locked;
            this.queue = queue;
        }
    
        @Override
        public void run() {
            try {
                this.locked.await();
                while (true) {
                    if (this.queue.isEmpty()) {
                        break;
                    }
                    System.out.println(String.format("消费线程 ThreadId = %s, Task = %s ", Thread.currentThread().getId(), this.queue.poll()));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(String.format("消费线程 %s 结束",Thread.currentThread().getId()));
            }
        }
    }
  • 相关阅读:
    C++库---json
    C++之单例模式
    mysql之字段(整形、字符串等)
    C++之数据类型,容器
    C++文件操作,判断两个文件内容是否相等(被修改)
    (转)mysql之index(索引)
    Django中的日期和时间格式 DateTimeField
    有关Django的smallDemo
    mysql 快速生成百万条测试数据
    从输入URL到页面加载发生了什么
  • 原文地址:https://www.cnblogs.com/fqybzhangji/p/11934140.html
Copyright © 2011-2022 走看看