同步模式之保护性暂停

保护性暂挂模式(Guarded Suspension Pattern)常用于一个线程等待去另一个线程的结果;

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()) { //使用while 防止虚假唤醒
                long delay = millis - now; //防止虚假唤醒后的超时等待
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

这里在上面代码基础上做简单修改,实现一个线程等待另一个线程;


public class GuardedTest {
    public static void main(String[] args) {

        GuardedObject guardedObject = new GuardedObject();
        new Thread(()->{
            try {
                Object o = guardedObject.get(0);
                System.out.println(o);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();


        new Thread(()->{
            try {
                Thread.sleep(9000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            guardedObject.set(999);
        },"t2").start();
    }
}

class GuardedObject{

    private Object object;

    public final synchronized Object get(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 (object ==null) {
                wait(0);
            }
        } else {
            while (object == null) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
        return object;
    }

    public final synchronized void set(Object object){
        this.object = object;
        this.notify();
    }
}

相关知识点:

synchronized:保证原子性和可见性; 

sleep():不释放对象锁:

wait():释放对象锁,可能存在虚假唤醒,需配合synchronized使用;

synchronized修饰方法时,未使用static时,锁对象时当前对象this;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值