java多线程wait()、notify()、notifyAll()的使用

wait():线程调用了对象的 wait()方法,线程进入阻塞状态,线程会释放对象的锁
notify():当有线程调用了对象的 notify()方法会随机唤醒一个 wait 线程,被唤醒的的线程便会进入就绪状态竞争该对象的锁
notifyAll():当有线程调用了对象的 notifyAll()方法会唤醒所有 wait 线程,被唤醒的的线程便会进入就绪状态竞争该对象的锁

使用注意事项:
1)wait() 与 notify/notifyAll 方法必须,获得该对象的锁,以保证同步。
2)尽量不要在notify/notifyAll()后面再写一些耗时的代码,导致锁一直不释放
3)notify可能会导致死锁,所以尽量使用notifyAll()

使用示例(等待超时模式):

public class WaitNotify {
    private boolean flag;

	private long timeOut;
    public WaitNotify(boolean flag) {
        this.flag = flag;
        this.timeOut = timeOut;
    }

    public synchronized void notifyAllWait(boolean flag){
    	this.flag = flag;
    	notifyAll();
    	//其他的业务代码
    }
    //超时线程数
	static AtomicInteger overtimeCount = new AtomicInteger();
    public synchronized void waitNotify(long timeOut){
    	//剩余时长
		long remaining =  timeOut;
		//超时时间
		long overtime = System.currentTimeMillis()+remaining;
		while(!flag && remaining>0) {
    		try {
				wait();
				remaining = overtime - System.currentTimeMillis();
				System.out.println(Thread.currentThread().getName()+"超时时间"+overtime
						+"剩余时长"+remaining+"] is be notifed.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if(remaining <= 0){
			System.out.println(Thread.currentThread().getName()+"超时了");
			overtimeCount.incrementAndGet();
		}
	}



	public static void main(String[] args) {
		WaitNotify waitNotify = new WaitNotify(false);
		Random r = new Random();
		for(int i=0;i<3;i++){//三个线程
			new Thread(new Runnable() {
				@Override
				public void run() {
					waitNotify.waitNotify(r.nextInt(1000));
				}
			}).start();
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//超时线程数小于当前线程数时,继续唤醒所有未超时线程
		while(WaitNotify.overtimeCount.get() < 3){
			waitNotify.notifyAllWait(false);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}


	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值