线程等待通知机制
一、超时模式范式
如果等待时长为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 代码实现:
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 {
Shop shop = new Shop("nothing");
new MyThread(shop, 2000).start();
new MyThread(shop, 500).start();
new MyThread(shop, 100).start();
Thread.sleep(1000);
shop.sendToy("babiwawa");
}
}
四、参考