【Java并发】同步模式之保护性暂停

public class 设计模式_保护性暂停 {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(()->{
            guardedObject.doWorkSetResponse("1");
        },"楠哥").start();

        new Thread(()->{
            guardedObject.waitResponse(2000);
        },"熊哥").start();
    }
}

class GuardedObject{
    private String response;
    public String waitResponse(long timeout){
        long begin = System.currentTimeMillis();
        synchronized (this){
            long parseTime = 0;
            while (response == null){
                long rest = timeout - parseTime;
                if (rest<0){
                    rest = 0;
                }
                try {
                    System.out.println("熊哥叫楠哥去吃饭,但是楠哥不在,熊哥开始等楠哥睡醒......");
                    wait(rest);
                    if (timeout-(System.currentTimeMillis() - begin)<=0){
                        System.out.println("熊哥给楠哥发消息:饿死了,不等你了,我先走了.......");
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                parseTime = System.currentTimeMillis() - begin;
            }
        }
        return response;
    }

    public void doWorkSetResponse(String response){
        System.out.println("楠哥正在睡觉......");
        try {
            Thread.sleep(6000);
            System.out.println("6 hours later......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this){
            this.response = response;
            notifyAll();
        }
        System.out.println("楠哥睡醒了,告诉了熊哥");
    }
}

用于一个线程等待另一个线程的消息。
和join相比的好处:
join只有在一个线程结束之后,下一个线程才会被唤醒。而保护性暂停模式可以在线程运行中给另外一个线程传递信号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值