等待唤醒机制

   Java多线程中等待唤醒机制.

   wait,notify,notifyAll.三个方法都是对持有锁的线程操作,所以使用在同步过程中.

   为什么这些方法定义在Object类中呢?让一个线程等待和唤醒一个线程,必须使用的是同一把锁.不可以对不同锁的线程进行唤醒.而锁可以是任意对象,可以被任意对象调用的方法定义在Object类中.

  

package com.neutron.thread.wait_notify;
/**
 * 线程通信中共享信息类
 * @author zhanght
 *
 */
public class Resource {
	private String name;
	private int age;
	private boolean flag = false;
	
	public synchronized void setResource(String name, int age) {
		if(this.flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.name = name;
		this.age = age;
		flag = true;
		this.notify();
	}
	
	public synchronized void getResource() {
		if (!this.flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("name:" + this.name + ", age:" + age);
		flag = false;
		this.notify();
	}
	
	
	public static void main(String[] args){
		Resource res = new Resource();
		new Thread(new Input(res)).start();
		new Thread(new Output(res)).start();
	}
}
    
package com.neutron.thread.wait_notify;
/**
 * 数据输入
 * @author zhanght
 *
 */
public class Input implements Runnable {
	private Resource res;
	public Input(Resource res) {
		this.res = res;
	}
	
	@Override
	public void run() {
		int x = 0;
		while(true) {
			if (x == 0) {
				res.setResource("sky", 11);
			} else {
				res.setResource("sea", 21);
			}
			x = (x + 1) % 2;
		}
	}

}
package com.neutron.thread.wait_notify;

public class Output implements Runnable {
	private Resource res;
	public Output(Resource res) {
		this.res = res;
	}
	
	@Override
	public void run() {
		while(true) {
			res.getResource();
		}
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值