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只有在一个线程结束之后,下一个线程才会被唤醒。而保护性暂停模式可以在线程运行中给另外一个线程传递信号。