首页 > 编程语言 > 详细

Java完成生产者消费者模型

时间:2017-03-10 17:35:16      阅读:156      评论:0      收藏:0      [点我收藏+]

生产者和消费者模型,是多线程中的典型模型,这里使用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();
    }
    
}

测试结果:

技术分享

 

Java完成生产者消费者模型

原文:http://www.cnblogs.com/djoker/p/6531533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!