wait()和notify()的使用(来源于网络)

在使用wait()的时候,一定要放到synchronized块中,或者把方法定义为synchronized,不然会出现错误提示 current thread not owner。

synchronized块的执行效率比synchronized方法快很多,所以除非有特殊理由,一般情况下优先使用synchronized块。

同样,在其他线程中调用wait()线程的notify()或者是notifyAll()时,也要注意一定要使用synchronized,不然将无法找到线程。示例如下


class Exercise08A extends Thread {
	public Exercise08A() {
		start();
	}

	public void run() {
		try {
			System.out.println("waiting start");
			synchronized (this) {
				wait();
			}
			System.out.println("waiting end");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Exercise08B extends Thread {
	Exercise08A ea;

	public Exercise08B(Exercise08A ea) {
		this.ea = ea;
		start();
	}

	public void run() {
		try {
			System.out.println(" before notifyAll() ");
			synchronized (ea) {
				ea.notify();
			}
			System.out.println(" after notifyAll()");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值