线程通信--生产者消费者案例wait,notify解决

本文介绍了一个基于Java实现的生产者消费者模式案例。通过synchronized关键字和wait/notify机制确保线程间的正确同步,使得生产者线程负责向共享资源中放入数据(如“春哥”、“凤姐”等),而消费者线程负责从中取出并打印数据。此模式有效地解决了多线程之间的数据同步问题。
public class ShareResource {
	private String name;
	private String gender;
	private boolean isEmpty=true;  //表示共享资源对象是否为空的状态
	//存储数据
	synchronized public void push(String name,String gender) {
		try {
			while(!isEmpty) {
				//当前isEmpty为false的时候,不空等着消费者来获取
				//使用同步锁对象来调用,表示当前线程释放同步锁,进入等待池,只能被其他线程唤醒
				this.wait();
		 }
			//------生产开始------
			this.name=name;
			Thread.sleep(10);
			this.gender=gender;
			//-----生产结束-------
			isEmpty=false;  //设置共享资源不为空
			this.notify();  //唤醒一个消费者
		
	   }catch(Exception e) {
		   e.printStackTrace();
	   }
		
	}
    //取出数据
	synchronized public void popup(){
		try {
			while(isEmpty) {
				//当前isEmpty为false的时候,不空等着消费者来获取
				//使用同步锁对象来调用,表示当前线程释放同步锁,进入等待池,只能被其他线程唤醒
				this.wait();
		 }
		Thread.sleep(10);	
		System.out.println(this.name+"--"+this.gender);
		isEmpty=true;
		this.notify();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
public class Producer implements Runnable{
     private ShareResource resourse=null;
     public Producer(ShareResource resource) {
		this.resourse=resource;
     }
     public void run() {
    	 for(int i=0;i<500;i++) {
    		 if(i % 2 == 0) {
    			 resourse.push("春哥", "男");
    		 }else {
    			 resourse.push("凤姐", "女");
    		 }
    	 }
     }
}
public class Consumer implements Runnable{
	private ShareResource resource=null;
	public Consumer(ShareResource resource) {
		this.resource=resource;
	}
	public void run() {
		for(int i=0;i<500;i++) {
			resource.popup();
		}
	}
}
public class App {

	public static void main(String[] args) {
		ShareResource resource=new ShareResource();
		new Thread(new Producer(resource)).start();
		new Thread(new Consumer(resource)).start();
		
	}

}

多个生产者,消费者就notify(只能唤醒任意一个线程)换成notifyAll
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值