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()));
            }
        }
    }
  • 相关阅读:
    div布局改进treeview导航
    WEB框架研究笔记八(HIBERNATE)
    WEB框架研究笔记四(Spring Framework)
    WEB框架研究笔记二(Extjs调用Struts)
    WEB框架研究笔记九(PowerDesigner)
    WEB框架研究笔记七(Spring2+struts2)
    WEB框架研究笔记十(JPA)
    WEB框架研究笔记11(第一阶段完成)
    WEB框架研究笔记五(Spring Aop)
    WEB框架研究笔记三(连接数据库)
  • 原文地址:https://www.cnblogs.com/fqybzhangji/p/11934140.html
Copyright © 2011-2022 走看看