线程间通讯和等待唤醒机制

示例:生产和消费

要求:使用多线程,生产一个就消费一个


代码:

public class Thread_Demo4 {

	public static void main(String[] args) {
		
		// 实例化资源
		Resouces res = new Resouces();
		
		// 实例化生产和消费者
		Producer pro = new Producer(res);
		Consumer con = new Consumer(res);
		
		// 创建两个生产线程和两个消费线程
		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		Thread t3 = new Thread(con);
		Thread t4 = new Thread(con);
		
		// 启动线程
		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}

	// 资源类
	static class Resouces {
		private String name;
		private int count = 1;
		private boolean isRn = false;

		// 生产商品
		public synchronized void set(String name) {
			
			while (isRn) {
				try {
					// 冻结线程
					this.wait();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 设置生产名称和编号
			this.name = name + "--" + count++;
			System.out.println(Thread.currentThread().getName() + "--正在生产---"
					+ this.name+"份");
			isRn = true;
			// 唤醒所有冻结的线程
			this.notifyAll();

		}

		// 消费商品
		public synchronized void out() {
			
			while (!isRn) {
				try {
					// 冻结线程
					this.wait();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName()
					+ "----已经消费------" + this.name+"份");
			isRn = false;
			// 在本线程冻结之前唤醒所有其它被冻结的线程
			this.notifyAll();
		}

	}

	// 生产者
	static class Producer implements Runnable {
		private Resouces res;
		Producer(Resouces res) {
			this.res = res;
		}
		public void run() {
			while (true) {
				res.set("汉堡");
			}
		}

	}

	// 消费者
	static class Consumer implements Runnable {
		private Resouces res;
		Consumer(Resouces res) {
			this.res = res;
		}
		public void run() {
			while (true) {
				res.out();
			}
		}
	}
}

线程间通讯和等待唤醒机制
 * 
 * 是指多个线程在操作同一个资源,担是操作的动作不同
 * wait():冻结线程
 * notify():唤醒冻结中的第一个线程
 * notifyAll():唤醒所有冻结的线程
 * 它们都是使用在同步中,因为要对持有监视器(锁)的线程操作
 * 所以要使用在同步中,因为只有同步才具有锁
 * 
 * 担是wait,notify,notifyAll这些方法要定义在Object中呢?
 * 因为这些方法在操作同步线程时,都必需要标识它们所操作线程持有的锁
 * 只有同一个锁上的被等待的线程,可以被同一个锁上的notify唤醒
 * 不可能对不同锁中的线程进行唤醒
 * 也就是说,等待和唤醒必需是同一个锁。
 * 需锁可能是任意对象,所以可以被任意对象调用的方法定义在Object类中。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值