释放所有等待的线程

时间:2016-07-03 23:41:29

标签: java multithreading java-threads barrier

我正在写这个模拟障碍点的课程。当线程到达此屏障点时,它不能继续,直到其他线程也达到此点。我正在使用计数器来跟踪此时到达的线程数。假设该类期望N + 1个线程,但只给出N个线程。在这种情况下,程序将保持所有线程等待,因为它认为还有一个线程要到达。

我想写一个允许我释放所有等待线程的方法,无论程序是否认为还有更多线程到达障碍点。

我的程序等待所有线程,

var xs = ['foo.js', 'bar.js', 'baz.js'].map(require);

我以为我可以简单地创建一个调用public volatile int count; public static boolean cycle = false; public static Lock lock = new ReentrantLock(); public static Condition cv = lock.newCondition(); public void barrier() throws InterruptedException { boolean cycle; System.out.println("lock"); lock.lock(); try { cycle = this.cycle; if (--this.count == 0) { System.out.println("releasing all threads"); this.cycle = !this.cycle; cv.signalAll(); } else { while (cycle == this.cycle) { System.out.println("waiting at barrier"); cv.await(); // Line 20 } } } finally { System.out.println("unlock"); lock.unlock(); } } 方法的方法,所有线程都是免费的。但是,我遇到的一个问题是,如果程序期望更多线程,它将保持锁定,因为它将在第20行等待。

有没有办法绕过这个锁?我该如何处理这个问题?

1 个答案:

答案 0 :(得分:0)

更好的想法 - 使用标准的java.util.concurrent原语 - 循环方法'方法'重置':

/**
 * Resets the barrier to its initial state.  If any parties are
 * currently waiting at the barrier, they will return with a
 * {@link BrokenBarrierException}. Note that resets <em>after</em>
 * a breakage has occurred for other reasons can be complicated to
 * carry out; threads need to re-synchronize in some other way,
 * and choose one to perform the reset.  It may be preferable to
 * instead create a new barrier for subsequent use.
 */
public void reset()