Java_生产者与消费者模型_synchronized_wait_notifyAll

生产者与消费者,三个主要关键字:synchronized_wait_notifyAll

 

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

public class ProCustom_value<T> {
    private LinkedList<T> lists=new LinkedList<>(); 
    private int MAX=10; //最多装10
    private int count=0; //当前0个

    /*
     * 生产者
     */
    public synchronized void put(T t){
        while(lists.size() == MAX){ //装满了//循环检查
	    try{
		this.wait(); //阻塞,释放锁,wait和while绝配
	    }catch(InterruptedException e){
		e.printStackTrace();
	    }
	}
	System.out.println(Thread.currentThread().getName()+"生产-->"+t);
	lists.add(t);
	++count;
	this.notifyAll(); //通知消费者线程进行消费
    }
	
    /*
     * 消费者
     */
    public synchronized T get(){
        T t=null;
	while(lists.size()==0){
	    try {
		this.wait();
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
	t=lists.removeFirst();
	count--;
	this.notifyAll(); //通知生产者生产
	return t;
    }
	
    public static void main(String[] args) {
        final ProCustom_value<String> c=new ProCustom_value<>();
	//启动消费者线程
	for(int i=0;i<10;i++){
	    new Thread(new Runnable() { //创建10个线程消费
		public void run() {
		    while(true){
                        System.out.println("消费-->"+c.get());
		    }
		}
	    },"c"+i).start();
	}
	
	try {
            TimeUnit.SECONDS.sleep(2); //睡2秒
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
		
	//启动生产者线程
	for(int i=0;i<2;i++){
	    new Thread(new Runnable() {
	        public void run() {
		    while(true){    			                                                               
		        c.put(Thread.currentThread().getName()+"食品");
                    }
				}
		},"p"+i).start();
	    }
	}
}
















mark:学习笔记

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值