Java多线程——线程间通信:生产者与消费者(wait(),notify())

生产者与消费者问题:

有两个或者多个线程。 其中一个/一部分线程,生产“数据”,称为生产者线程;
另一个/一部分线程,消耗“数据”,称为消费者线程。
这些数据放在一个“共享”区域。

那么就会出现:
当“共享”区域中的数据空了,消费者线程必须"停/等待",等待到产者线程生产了新数据后,继续进行。
当“共享”区域中的数据满了,生产者线程必须"停下/等待",等到消费者线程消耗了数据后,继续进行。

涉及内容:
(1)共享数据: 就会有线程安全问题,就需要同步 (synchronize)
(2)共享区域大小固定且有限:需要线程"协作通信"(wait(),notify())

线程之间的通信:wait()和notify()

(1)wait():必须由锁对象(线程的监视器对象)来调用。调用后使当前线程等待,并且释放锁。
(2)notify():必须由锁对象(线程的监视器对象)来调用。唤醒一个正在等待的线程。唤醒的是同一个锁对象监视的等待线程(既可能是生产者也可能是消费者)。注:不是说生产者释放锁一定唤醒消费者,反之亦然。
(3)notifyAll():唤醒所有和我是同一个监视器对象的正在等待的线程。一般用于多个生产者和消费者,之所以不用notify是因为notify()是随机唤醒一个线程,在多个生产者和消费者的情况下可能出现一种情况(唤醒顺序)就是全员处于wait状态造成阻塞。虽然说概率极小,但还是要注意。

不要把释放锁与唤醒线程搞混,释放锁并不会唤醒线程,一定要notify,上篇文章: 线程安全.中之所以没有用notify,是因为两个线程一直在执行,并没有wait,要搞清楚wait和notify保证的是线程之间的通信,释放锁是其次,synchronize保证的是数据的安全。

一个生产者,一个消费者:

public class Test {
	
	public static void main(String[] args) {
	
		storehouse store=new storehouse();
		
		Producer p = new Producer("生产者", store);
		Consumer c = new Consumer("消费者", store);
		c.start();
		p.start();
		
	}
}
	
class storehouse{
	//仓库容量为10
	public  int MAX = 10;
	public  int count;

}

class Producer extends Thread{
	private storehouse store;

	public Producer(String name, storehouse store) {
		super(name);
		this.store = store;
	}

	public void run(){
		while(true){
			synchronized (store) {	
				if(store.count >= store.MAX){
					try {		
						store.wait();//释放锁
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}							
				//因为有程序计数器,当前线程被唤醒后,紧接着上次后面的代码执行	
				store.count++;				
				System.out.println(Thread.currentThread().getName() + "生产+1,剩余:" + store.count);
				store.notify();	//唤醒任意等待线程,为避免自己再次抢到锁,所以让当前线程先睡眠半秒钟	
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				
		}
	}
}
class Consumer extends Thread{
			
	private storehouse store;
		
	public Consumer (String name, storehouse store) {
		super(name);
		this.store = store;
	}

	public void run(){
		while(true){
			synchronized(store)
			{
				if(store.count<=0){
					try {									
						store.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}					
				store.count--;
				System.out.println(getName() + "消费-1,剩余:" + store.count);
				store.notify();	
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			  }			
		}		
	}
}

在这里插入图片描述

多个生产者,多个消费者

type1:

public class Test {
	
	public static void main(String[] args) {
	
		storehouse store=new storehouse();
		
		Producer p = new Producer("生产者1", store);
		Producer p2=new Producer("生产者2", store);
		Consumer c = new Consumer("消费者1", store);
		Consumer c2 = new Consumer("消费者2", store);
		Consumer c3 = new Consumer("消费者3", store);
		c2.start();
		c3.start();
		c.start();
		p.start();
		p2.start();
	}
}
	
class storehouse{
	//仓库容量为10
	public  int MAX = 10;
	public  int count;

}

class Producer extends Thread{
	private storehouse store;

	public Producer(String name, storehouse store) {
		super(name);
		this.store = store;
	}

	public void run(){
		while(true){
			synchronized (store) {					
				while(store.count >= store.MAX){
					try {		
						store.wait();//也会释放锁
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}								
				store.count++;				
				System.out.println(Thread.currentThread().getName() + "生产+1,剩余:" + store.count);
				store.notifyAll();		
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				
		}
	}
}
class Consumer extends Thread{
			
	private storehouse store;
		
	public Consumer (String name, storehouse store) {
		super(name);
		this.store = store;
	}

	public void run(){
		while(true){
			synchronized(store)
			{				
				while(store.count<=0){
					try {									
						store.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}								
				store.count--;
				System.out.println(getName() + "消费-1,剩余:" + store.count);
				store.notifyAll();	
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			  }			
		}		
	}
}

注意多线程之间的虚假唤醒

原因:在java多线程判断时,不能用if,程序会在判断上面出错。某一线程如果此时已经处于wait状态,被唤醒时会直接向下继续执行代码,而不会再做一次执行判断,进而可能会出现错误。
所以要用loop循环,if只判断一次,while是只要唤醒就要拉回来再判断一次。

释放锁的时机

什么情况下会释放锁?
(1)同步代码块或同步方法中的代码运行完了。
(2)wait()
(3)遇到异常,但是没有处理,这个线程死了,会释放锁

什么情况下不会释放锁?
(1)sleep()
(2)yield()
(3)suspend()

wait()和sleep()的区别?

(1)wait()释放锁和sleep()不释放
(2)wait()是Object类中声明
sleep()是Thread类中声明的
(3) wait()必须有“锁,监视器”对象来调用,如果由别的对象调用会报IllegleMoniterStateException
sleep()是静态方法,Thread类名调用就可以
(4)wait()使得当前线程进入阻塞状态后,由notify唤醒
sleep()使得当前线程进入阻塞状态后,时间到或被interrupt()醒来。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GuochaoHN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值