wait、notify、join和保护性暂停模式

wait和notify是Object的方法,前者用于让运行的线程阻塞进入TIMED_WAITING模式,后者用于通知相同锁对象阻塞的线程继续运行。

一般地使用模式为:

Object lock = new Object();
function1(){
    syncronized(lock){
        while(条件不满足){
            lock.wait();
        }
        TODO other things...
    }
}

function2(){
    syncronized(lock){
        lock.notify();
        //lock.notifyAll();
    }
}

保护性暂停模式即可以使用这种方式实现。保护性暂停即是说一个线程要拿到结果,需要等待另外的线程。

我们可以设计一个同步类。

class GuardObject{
    Object lock = new Object();
    Object result = null;
    pubblic Object get(){
        syncronized(this){
            while(null == result){
                wait();
            }
            return result;
        }
    }

    public void complete(Object result){
        syncronized(this){
            this.result=result;
            notify();
            //notifyAll();
        }
    }
}

当结果还没有的时候,get方法所在线程就一直等待,直到另外的线程得到结果后通知。

更进一步的,get()方法可以设置超时时间。Thread类的join方法也类似这种模式。

public final synchronized void join(long millis)
    throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值