簡體   English   中英

釋放所有等待線程

[英]Free all waiting threads

我正在編寫模擬障礙點的此類。 當一個線程到達此障礙點時,除非其他線程也到達此點,否則它無法繼續進行。 我正在使用一個計數器來跟蹤此時已到達的線程數。 假定該類期望使用N + 1個線程,但是僅給定N個線程。 在這種情況下,程序將等待所有線程,因為它認為還有一個線程要到達。

我想寫一個方法,使我可以釋放所有等待的線程,而不管程序是否認為仍有更多線程到達障礙點。

我的程序要等待所有線程,

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();
    }
}

我以為我可以簡單地創建一個調用signalAll()方法的方法,並且所有線程都是空閑的。 但是,我遇到的一個問題是,如果程序期望更多線程,它將保持鎖定,因為它將在第20行等待。

有辦法解決這個問題嗎? 我應該如何解決這個問題?

更好的主意-使用標准java.util.concurrent原語-帶有方法'reset'的CyclicBarrier:

/**
 * 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM