java线程通信-生产者消费者

1 调用wait()方法可以让线程等待,并释放对象锁,直到interrupt()方法中断它或者另一个线程调用notify()或者notify()All唤醒

2.wait()方法可以带个参数,此时不需要唤醒

3.调用notify()方法可以随机选择一个在该对象调用wait()方法的线程

4.notif和notifyAll()只能在同步方法或者同步块中使用

5.wait()和sleep()的区别是:wait()方法调用时会释放对象锁,而sleep()不会

以下为生产者消费者的例子:




public class ProRes {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Product product=new Product();
		Producer producer=new Producer(product);
		Consumer consumer=new Consumer(product);	}

}

class Product{
	int n;
	boolean valueset=false;//true表示有值可取,false便是需要放入新值
	//消费方法
	synchronized void get(){
		//如果没有值,等待新值放入
		if(!valueset){
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println(Thread.currentThread().getName()+"-Get:"+n);
		//将valuset设置为false表示已取值
		valueset=false;
		//通知等待线程,放入新值
		notify();
	}
	//消费方法
	synchronized void put(int n){
		//如果没有值,等待线程取值
		if (valueset) {
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		this.n=n;
		//将valueset设置为true,表示值已放入
		valueset=true;
		System.out.println(Thread.currentThread().getName()+"-put:"+n);
		notify();
	}
}
class Producer implements Runnable{

	
		Product product;
		Producer(Product product){
			this.product=product;
			new Thread(this,"Producer").start();
		}
		public void run() {
			int k=0;
			for (int i = 0; i < 5; i++) {
				product.put(k++);
				
			}
	}
	
}
class Consumer implements Runnable{
	Product product;
	Consumer(Product product){
		this.product=product;
		new Thread(this,"Consumer").start();
	}

	public void run() {
		
		//消费五次
		for (int i = 0; i < 5; i++) {
			product.get();
			
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值