首页 > 代码库 > 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();
    }
    
}

测试结果:

技术分享

 

Java完成生产者消费者模型