Shop类
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");
}
}