03-Java多线程、线程等待通知机制

线程等待通知机制

一、超时模式范式

如果等待时长为T,当前时间为now,那么now+T以后超时
long overtime = now+T
long remain = T
while(result不满足 && remian>0){
    wait(remian); //等待,最多等待remian的时间
    remain = overtime - now;
}
   return result;

二、自定义连接池

2.1 代码实现:

三、线程等待通知

  • wait/notify结合超时范式实现等待通知机制

3.1 代码实现:

//Shop类模拟商店,初始状态玩具是nothing,线程等待玩具,一旦有玩具了会通知等待的线程
public class Shop {

    //商店里面的玩具
    private String toy;

    public Shop(String toy) {
        this.toy = toy;
    }

    //等待玩具,如果没有玩具就阻塞,一旦有玩具了,会唤醒等待玩具的线程
    public synchronized void waitToy(long mills) {
    	//起始时间
        long begin = System.currentTimeMillis();
        //可以等待的剩余时间
        long remain = mills;
        //等待的截止时间
        long end = System.currentTimeMillis() + mills;
        while ("nothing".equalsIgnoreCase(toy) && remain > 0) {
            try {
               //等待的最大时间不能超过剩余时间
                wait(remain);
                //等到一段时间之后,需要重新计算剩余时间
                remain = end - System.currentTimeMillis();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //说明是等待超时退出
        if ("nothing".equalsIgnoreCase(toy)) {
            System.out.println(Thread.currentThread().getName() + "线程不等待了,等待了"
                    + (System.currentTimeMillis() - begin) + " ms 了...");
        } else {
            System.out.println(Thread.currentThread().getName() + "收到了通知,有玩具 " + toy + " 了...");
        }

    }

    //玩具到货了,玩具到货之后通知等待玩具的线程
    public synchronized void sendToy(String toy) {
        this.toy = toy;
        System.out.println("玩具到货了...");
        notifyAll();
    }
}

//测试类:初始化三个线程等待玩具,一段时间后玩具有了,但是等待线程可以自定义等待时间,只有还在等待的线程会收到通知。
 public class ShopTest {
    static class MyThread extends Thread {

        Shop shop;
        long mills;

        public MyThread(Shop shop, long mills) {
            this.shop = shop;
            this.mills = mills;
        }

        @Override
        public void run() {
            shop.waitToy(mills);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //1.初始化玩具店,最初没有玩具
        Shop shop = new Shop("nothing");

        //2.等待玩具的线程
        new MyThread(shop, 2000).start();
        new MyThread(shop, 500).start();
        new MyThread(shop, 100).start();

        Thread.sleep(1000);

        //3.玩具到货
        shop.sendToy("babiwawa");

    }
}

 

四、参考

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值