zoukankan      html  css  js  c++  java
  • Java完成生产者消费者模型

    生产者和消费者模型,是多线程中的典型模型,这里使用Java完成该模型

    ServerTest.java 生产者代码

    package com.orange.threadmodel;
    
    import java.util.Queue;
    
    public class ServerTest implements Runnable{
    
        private Queue<String> queue;
        
        public ServerTest(Queue<String> queue){
            this.queue = queue;
        }
            
        @Override
        public void run() {
            while(true){
                try{
                    if(queue.size() < 10){
                        System.out.println("生成商品......");
                        queue.offer("String-->");
                        Thread.sleep(1000);
                    }else{
                        System.out.println("无法生成商品,库存满了");
                        Thread.sleep(3000);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }        
    }

    ClientTest.java 消费者代码

    package com.orange.threadmodel;
    
    import java.util.Queue;
    
    public class ClientTest implements Runnable{
    
        private Queue<String> queue;
        
        public ClientTest(Queue<String> queue){
            this.queue = queue;
        }
        
        @Override
        public void run() {
                while(true){
                    try{
                        if(queue.isEmpty()){
                            System.out.println("商品消费完了,无法再消费......");
                            Thread.sleep(10000);
                        }else{
                            System.out.println("消费商品......");
                            queue.poll();
                            Thread.sleep(20000);
                        }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
    }

    ModelClient.java 测试模型代码

    package com.orange.threadmodel;
    
    import java.util.Queue;
    import java.util.concurrent.ArrayBlockingQueue;
    
    public class ModelClient {
    
        private static Queue<String> queue = new ArrayBlockingQueue<String>(10);
        
        public static void main(String[] args){
            ServerTest st = new ServerTest(queue);
            ClientTest ct = new ClientTest(queue);
            Thread t1 = new Thread(st);
            Thread t2 = new Thread(ct);
            t1.start();
            t2.start();
        }
        
    }

    测试结果:

  • 相关阅读:
    详解MathType中如何插入特殊符号
    详解如何将MathType嵌入word中
    MathType公式编辑器快捷键操作
    MathType初级教程:怎么安装MathType
    AOPR密码过滤器
    教您如何在Word的mathtype加载项中修改章节号
    在word文档中如何插入Mathtype公式
    详解MathType中如何更改公式颜色
    静态缓存和动态缓存
    ThinkPHP U函数生成URL伪静态
  • 原文地址:https://www.cnblogs.com/djoker/p/6531533.html
Copyright © 2011-2022 走看看