0%

保护性暂停

定义

即Guarded Suspension,用在一个线程等待另一个线程的执行结果

要点:

  • 有一个结果需要从一个线程传递到另一个线程,让他们关联同一个GuradedObject
  • 如果有结果不断从一个线程到另一个线程那么可以使用消息队列(见生产者、消费者模式)
  • JDK中,join的实现,future的实现,采用的就是此模式
  • 因为要等待另一方的结果,因此归类到同步模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class GuardedSuspension {
public static void main(String[] args) {

Guarded guarded = new Guarded();
new Thread(() -> {
Object o = guarded.get(1500);
System.out.println(o);
}).start();

new Thread(() -> {
try {
Thread.sleep(3000);
String nihao = "nihao";
guarded.complete(nihao);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}

class Guarded{
private Object response;

public Object get(long timeout) {
synchronized (this){
long begin = System.currentTimeMillis();
long passedTime = 0;
while(response == null && passedTime <= timeout) {
try {
this.wait(timeout - passedTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
passedTime = System.currentTimeMillis() - begin;
}
}
return response;
}

public void complete(Object response) {
synchronized (this){
this.response = response;
this.notifyAll();
}
}
}