0

我遇到了这个障碍代码,我无法理解该barrierPost方法。

我应该使用此代码来解决一个练习,其中两个线程团队相互竞争以计数到 10000。

我不明白为什么相同的条件会产生相反的结果

public class Barrier {

    private int currentPosters = 0, totalPosters = 0;
    private int passedWaiters = 0, totalWaiters = 1;

    /**
     * @param totalPosters - Nr of threads required to start the waiting threads
     * @param totalWaiters - Nr of threads started later 
     */
     public Barrier (int totalPosters, int totalWaiters) {
     this.totalPosters = totalPosters; 
     this.totalWaiters = totalWaiters;

    }

    public synchronized void init(int i) {
        totalPosters = i; currentPosters=0;
    }

    public synchronized void barrierSet(int i) {
        totalPosters = i; currentPosters=0;
    } 

    public synchronized void barrierWait() {
        boolean interrupted = false;
        while (currentPosters = totalPosters) {
            try {wait();} 
            catch (InterruptedException ie) {interrupted=true;}
        }
        passedWaiters++;
        if (passedWaiters == totalWaiters) {
            currentPosters = 0; passedWaiters = 0; notifyAll();
        }
        if (interrupted) Thread.currentThread().interrupt();
    }

    public synchronized void barrierPost() {
        boolean interrupted = false;   // In case a poster thread beats barrierWait, keep count of posters.
        while (currentPosters == totalPosters) { 
            try {wait();} 
            catch (InterruptedException ie) {interrupted=true;}
        }
        currentPosters++;
        if (currentPosters == totalPosters) notifyAll();
        if (interrupted) Thread.currentThread().interrupt();
   }
} 

有人可以帮忙吗?

4

0 回答 0