JavaSE 线程通信 wait() notify()

wait() 和notify()都是Object类的方法,实现thread和另外thread的通信。

主要要点:

一、当thread执行了wait()方法时,会释放掉它所持的对象锁,进入到wait pool中等待,等待被其他线程notify()后进入到lock pool中等待。在lock pool中获得对象锁后,继续从wait()的下一句执行。

二、notify()和wait()都在synchronized中。

三、wait()和sleep()的区别:

a) sleep()是Thread类的函数,wait()是所有类的对象都能obj,wait() 

b) sleep()不释放对象锁,休眠若干毫秒后醒来继续执行;wait()会释放掉对象锁,it will lose ownership of lock. 


实例:

用wait()和notify()实现4个threads之间的通信。 保证在0和1之间切换,当numberCount为0时,某线程+1操作,变为1; 当numberCount为1时,某线程-1操作,变为0.。。。。。一直在0、1之间跳转,不能跳到-1或2. 实例如下:

package com.syncronized.java;

public class TestNofity {

	public static void main(String[] args) {

		Example ex = new Example();

		ThreadIncrase thIn_1 = new ThreadIncrase(ex);
		ThreadIncrase thIn_2 = new ThreadIncrase(ex);

		ThreadDecrease thDe_1 = new ThreadDecrease(ex);
		ThreadDecrease thDe_2 = new ThreadDecrease(ex);

		thIn_1.start();
		thIn_2.start();
		thDe_1.start();
		thDe_2.start();

	}
}

class Example {
	private int numberCount;

	public synchronized void increase() {
		while(numberCount != 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (numberCount == 0) {
			numberCount++;
			System.out.println(numberCount);
		}
			this.notify();
		
	}

	public synchronized void decrease() {
		while(numberCount == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
			numberCount--;
			System.out.println(numberCount);
		
			this.notify();
		
	}

}

class ThreadIncrase extends Thread {
	private Example example;

	public ThreadIncrase(Example exam) {
		example = exam;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep((long) (1000 * Math.random()));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			example.increase();
		}
	}
}

class ThreadDecrease extends Thread {
	private Example example;

	public ThreadDecrease(Example exam) {
		example = exam;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep((long) (1000 * Math.random()));
			} catch (InterruptedException e) {

				e.printStackTrace();
			}

			example.decrease();
		}
	}
}

输出:

1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值