zoukankan      html  css  js  c++  java
  • java 生产者和消费者问题(线程)

    生产者,消费者模式

    package test;
    
    import java.util.Date;
    import java.util.LinkedList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
             EventStorage storage = new EventStorage();  
                Producer producer = new Producer(storage);  
                Thread thread1 = new Thread(producer); 
                Consumer consumer = new Consumer(storage);  
                Thread thread2 = new Thread(consumer); 
                thread1.start();
                thread2.start();
        }
    }
    /**
     * 缓冲区
     * @author Administrator
     *
     */
     class EventStorage{
        private int maxSize;//最大生产数
        private List<Date> storage;
        /*
         * 设置最大生产数
         */
        public EventStorage(){
            maxSize=10;
            storage=new LinkedList<Date>();
        }
            //设置线程等待方法
            public synchronized void set(){
                while(storage.size()==maxSize){
                    try {
                        wait();//等待
               System.out.println("调用方法set");
    } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } storage.add(new Date()); System.out.printf("Set: %d", storage.size()); } } public synchronized void get(){ while (storage.size()==0) { try { wait();
            System.out.println("调用方法get"); }
    catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } System.out.printf("Get: %d: %s", storage.size(),((LinkedList<?>)storage).poll()); notifyAll(); } }   

    /**
    *生产者类
    * @author Administrator
    *
    */

    class Producer implements Runnable{
        private EventStorage storge;
         public Producer(EventStorage storage){
             this.storge=storage;
         }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            for (int i = 0; i < 100; i++) {
                storge.set();
            }
        }
     }
     
    /**
    * 消费者类
    * @author Administrator
    *
    */
    class Consumer implements Runnable{ private EventStorage storage; public Consumer(EventStorage storage){ this.storage=storage; } @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i <100; i++) { storage.get(); } } }
  • 相关阅读:
    Webpack 入门指迷--转载(题叶)
    浏览器工作原理理解
    Knockout.js初体验
    node.js链接mysql
    2020年度春季学习总结--第二周
    Python 爬取 热词并进行分类数据分析-[安全性改造]
    以 CheatEngine 为例的六个质量属性
    2020年度春季学习总结--第一周
    软件架构师如何工作-个人见解
    Steam 游戏 《Crashlands(崩溃大陆)》修改器制作-[先使用CE写,之后有时间的话改用CheatMaker](2020年寒假小目标12)
  • 原文地址:https://www.cnblogs.com/lk617-home/p/8259753.html
Copyright © 2011-2022 走看看