如果需要多个类之间使用GuardedObject对象,作为参数传递不是很方便,因此设计一个解耦的中间类,这样不仅能够解耦结果的等待者和结果生产者,还能够支持多个任务的管理。
Futures就好比居民楼一层的信箱,每个信箱有房间的编号,左侧的t0,t2,t4就好比等待邮件的居民,右侧的t1,t3,t5就好比邮递员。
public class GuardedObjectMap {
public static void main(String[] args) {
//有三封信要送
for (int i = 0; i < 3; i++) {
new People().start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//邮递员送信
Set<Integer> ids = EmailBox.getIds();
for (int id: ids) {
new Postman(id, "内容"+id).start();
}
}
}
/**
* 居民
*/
class People extends Thread {
@O