Java:多线程Producer-Consumer的多种实现

多线程Producer-Consumer的多种实现


更多类型Product-Consumer的实现:https://github.com/Al-assad/Produer-Consumer

1、使用老式synchronized互斥锁实现:

/**
* @see
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:15:49
* @version V1.0  
* Description: Product-Consumer模型使用的Product类
*/

public class Product {
	private int typeId;  //产品种类编号 
	public Product(int typeId){
		this.typeId = typeId;
	}
	public int getType(){
		return this.typeId;
	}
	public String toString(){
		return "Product"+this.typeId; 
	}
}

/**
* @see Product
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 下午4:57:04
* @version V1.0  
* Description: product仓库类,负责维护products列表的同步更新;
*/

import java.util.*;

public class ProductRepository {
	
	private Queue<Product> products = new LinkedList<Product>();  //产品列表
	private final int limit;   //仓库中的产品最大存放量
	public ProductRepository(int limit){
		this.limit = limit;
	}
	//任务线程发送product对象到本products
	public synchronized void send(Product product) throws InterruptedException{
		while(products.size() >= limit)
			wait();
		products.offer(product);
//		System.out.println(products.size());  //打印仓库product数量
		notifyAll();
	}
	//任务线程从本products获取一个product对象
	public synchronized Product get() throws InterruptedException{
		while(products.size() == 0)
			wait();
		Product product = null;
		product = products.poll();
//		System.out.println(products.size());  //打印仓库product数量
		notifyAll();
		return product;
	}
	
	public synchronized Queue<Product> getProducts(){
		return products;
	}
	public int getLimit(){
		return limit;
	}


}

 @see Product.java ProductRepository.java
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:19:31
* @version V1.0  
* Description: Product-Consumer模型使用的Consumer类;
* 			   
*/
import java.util.concurrent.*;
import java.util.*;
public class Consumer implements Runnable{
	private ProductRepository repository;

	private static volatile int count = 0;  //记录累计Consumer的创建数量
	private int id = 0;    //记录Consumer的id
	
	public Consumer(ProductRepository repository){

		this.repository = repository;
		id = count;
		count++;
	}
	public String toString(){ 
		return "Producer"+id;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				Product product = repository.get();  //在这里可以通过product.getType()获取product种类,采取不同的处理操作
				System.out.println(this+" got "+product);
				TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));  //模拟消费时间
			}
		}catch(InterruptedException ex){
			System.out.println(this+" intrrupted!");
		}
		
	}
	
}

/**
* @see  Product.java ProductRepository.java
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:19:05
* @version V1.0  
* Description: Product-Consumer模型使用的Producer类
*/
import java.util.concurrent.*;
import java.util.*;
public class Producer implements Runnable{
    private ProductRepository repository;
    private int typeId;  //记录生产product的种类id
    private static volatile int count = 0;  //记录累计Producer的创建数量
    private int id = 0;    //记录Producer的id
    public Producer(ProductRepository repository,int typeId){
        this.typeId = typeId;
        this.repository = repository;
        id = count;
        count++;
    }
    public String toString(){
        return "Producer"+id;
    }
    public void run(){
        try{
            while(!Thread.interrupted()){
                Product product = new Product(typeId);  //生产工作分配到各线程,减少高创建成本对象的创建时间;
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));  //模拟生产时间
                System.out.println(this+" sent "+product);
                repository.send(product);
    
            }
        }catch(InterruptedException ex){
            System.out.println(this+" intrrupted!");
        }
        
    }
}

/**
* @see  Product.java ProductRepository.java Consumer.java Producer.java
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:25:00
* @version V1.0  
* Description: 单一种类product测试类;
*                每一个Driver实例只能实现一种类型的Product的交易;
*/
import java.util.concurrent.*;

public class Driver {
    private ProductRepository repository;
    private int typeId;     //指定该driver交易使用的product种类;
    public Driver(int typeId,int limit,int producerSize,int consumerSize,int runSec) throws InterruptedException{
        this.typeId = typeId;
        repository = new ProductRepository(limit);
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i=0;i<producerSize;i++)
            exec.execute(new Producer(repository,typeId));
        for(int i=0;i<consumerSize;i++)
            exec.execute(new Consumer(repository));
        TimeUnit.SECONDS.sleep(runSec);
        exec.shutdownNow();
    }
    public int getTypeId(){
        return this.typeId;
    }
/*    //Test
    public static void main(String[] args) throws InterruptedException{
        new Driver(0,10,20,25,10);
//        new Driver(1,8,10,10,10);
//        new Driver(2,15,12,5,10);
    }*/
    
    

}






2、使用BlockingQueue实现;

/**
* @see  Product.java 
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:19:05
* @version V1.0  
* Description: Product-Consumer模型使用的Producer类
*/
import java.util.concurrent.*;
import java.util.*;
public class Producer implements Runnable{
	private BlockingQueue<Product> products;
	private int typeId;  //记录生产product的种类id
	private static volatile int count = 0;  //记录累计Producer的创建数量
	private int id = 0;    //记录Producer的id
	public Producer(BlockingQueue<Product> products,int typeId){
		this.typeId = typeId;
		this.products = products;
		id = count;
		count++;
	}
	public String toString(){
		return "Producer"+id;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				Product product = new Product(typeId);  //生产工作分配到各线程,减少高创建成本对象的创建时间;
				TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));  //模拟生产时间
				products.put(product);
				System.out.println(this+" sent "+product);
			}
		}catch(InterruptedException ex){
			System.out.println(this+" intrrupted!");
		}
		
	}
}
/**
* @see Product.java 
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:19:31
* @version V1.0  
* Description: Product-Consumer模型使用的Consumer类;
*                
*/
import java.util.concurrent.*;
import java.util.*;
public class Consumer implements Runnable{
    private BlockingQueue<Product> products;
    private static volatile int count = 0;  //记录累计Consumer的创建数量
    private int id = 0;    //记录Consumer的id
    
    public Consumer(BlockingQueue<Product> products){
        this.products = products;
        id = count;
        count++;
    }
    public String toString(){ 
        return "Producer"+id;
    }
    public void run(){
        try{
            while(!Thread.interrupted()){
                Product product = products.take();  //在这里可以通过product.getType()获取product种类,采取不同的处理操作
                System.out.println(this+" got "+product);
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));  //模拟消费时间
            }
        }catch(InterruptedException ex){
            System.out.println(this+" intrrupted!");
        }
        
    }
    
}

/**
* @see
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:15:49
* @version V1.0  
* Description: Product-Consumer模型使用的Product类
*/

public class Product {
    private int typeId;  //产品种类编号 
    public Product(int typeId){
        this.typeId = typeId;
    }
    public int getType(){
        return this.typeId;
    }
    public String toString(){
        return "Product"+this.typeId; 
    }
}

/**
* @see  Product.java Consumer.java Producer.java
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月28日 上午1:25:00
* @version V1.0  
* Description: 单一种类product测试类;
*                每一个Driver实例只能实现一种类型的Product的交易;
*/
import java.util.concurrent.*;

public class Driver {
    private BlockingQueue<Product> products;
    private int typeId;     //指定该driver交易使用的product种类;
    public Driver(int typeId,int limit,int producerSize,int consumerSize,int runSec) throws InterruptedException{
        this.typeId = typeId;
        products = new ArrayBlockingQueue<Product>(limit);
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i=0;i<producerSize;i++)
            exec.execute(new Producer(products,typeId));
        for(int i=0;i<consumerSize;i++)
            exec.execute(new Consumer(products));
        TimeUnit.SECONDS.sleep(runSec);
        exec.shutdownNow();
    }
    public int getTypeId(){
        return this.typeId;
    }
    //Test
    public static void main(String[] args) throws InterruptedException{
        new Driver(0,10,20,25,10);
//        new Driver(1,8,10,10,10);
//        new Driver(2,15,12,5,10);
    }
    
    

}












  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用Java语言实现的生产者和消费者模型的示例: ``` import java.util.LinkedList; public class ProducerConsumerExample { public static void main(String[] args) { LinkedList<Integer> queue = new LinkedList<>(); int maxSize = 5; Producer producer = new Producer(queue, maxSize); Consumer consumer = new Consumer(queue); Thread producerThread = new Thread(producer, "Producer"); Thread consumerThread = new Thread(consumer, "Consumer"); producerThread.start(); consumerThread.start(); } } class Producer implements Runnable { private LinkedList<Integer> queue; private int maxSize; public Producer(LinkedList<Integer> queue, int maxSize) { this.queue = queue; this.maxSize = maxSize; } @Override public void run() { while (true) { synchronized (queue) { while (queue.size() == maxSize) { try { System.out.println("队列已满,生产者等待消费..."); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int number = (int) (Math.random() * 100); queue.add(number); System.out.println("生产者生产: " + number); queue.notifyAll(); } } } } class Consumer implements Runnable { private LinkedList<Integer> queue; public Consumer(LinkedList<Integer> queue) { this.queue = queue; } @Override public void run() { while (true) { synchronized (queue) { while (queue.isEmpty()) { try { System.out.println("队列为空,消费者等待生产..."); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int number = queue.removeFirst(); System.out.println("消费者消费: " + number); queue.notifyAll(); } } } } ``` 上述代码实现了一个简单的生产者和消费者模型,其中使用了一个线程安全的`LinkedList`队列作为生产者和消费者之间的缓冲区。在`Producer`和`Consumer`类中,`run()`方法被覆盖并实现了生产和消费的逻辑。 在生产者线程中,如果队列已满,则生产者线程将进入等待状态。当队列不满时,生产者线程将生成随机数并将其添加到队列中,并通过调用`notifyAll()`方法通知消费者线程可以消费了。在消费者线程中,如果队列为空,则消费者线程将进入等待状态。当队列不为空时,消费者线程将从队列中删除第一个元素,并通过调用`notifyAll()`方法通知生产者线程可以继续生产。 这种实现方式使用`synchronized`关键字确保在对队列进行修改时线程安全。此外,生产者和消费者线程之间的通信使用了`wait()`和`notifyAll()`方法,以确保生产者和消费者之间的协调。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值