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()));
            }
        }
    }
  • 相关阅读:
    记一次简单的正则表达式匹配实践
    使用readlines()读取文件时出现/n及其解决办法
    浅谈http和https
    JVM GC回收原理的认识
    Mysql中语言分类和区别
    关于storm程序性能压测记录及总结
    Java 集合框架
    MySQL binlog底层主从同步原理
    Docker-Compose安装
    gcc手动安装
  • 原文地址:https://www.cnblogs.com/fqybzhangji/p/11934140.html
Copyright © 2011-2022 走看看