来自JCIP的很少的房源已经出现在这里.这是另外一个(
orig. code):
public class ThreadGate { private boolean isOpen; private int generation; public synchronized void close() { isOpen = false; } public synchronized void open() { ++generation; isOpen = true; notifyAll(); } public synchronized void await() throws InterruptedException { int arrivalGeneration = generation; while (!isOpen && arrivalGeneration == generation) { wait(); } } }
书中评论:
The condition predicate used by await is more complicated than simply testing isOpen. This is needed because if N threads are waiting at the gate at the time it is opened, they should all be allowed to proceed. But, if the gate is opened and closed in rapid succession, all threads might not be released if await examines only isOpen: by the time all the threads receive the notification, reacquire the lock, and emerge from wait, the gate may have closed again. So ThreadGate uses a somewhat more complicated condition predicate: every time the gate is closed, a “generation” counter is incremented, and a thread may pass await if the gate is open now or if the gate has opened since this thread arrived at the gate.
伙计们,你们可能会笑,但我无法得到它:).问题:
>根据线程T1,T2,…和执行流程向我解释arrivalGeneration == generation的用法.
>为什么通道说每次关闭门时,生成计数器会递增?怎么回事?
谢谢大家!
最佳答案 问题#1:只要看看'(代理)所属的组’代’,允许整个组,所以如果门打开,组#会增加,并且属于已经等待的组的每个人都被允许在,即使门再次被视为“锁定”.
问题#2:我猜这是一个错误 – 它可能应该是’每次打开门时……’