开发者

Implement custom java barrier

I want to implement a custom java barrier. I don't want to use the CyclicBarrier class.

So all threads meet at a common point. The threads only procceed if all threads arrived at the barrier.

I want to use the wait/notify/notifyAll methods to implement the barrier.

So this is what I came up with

public class Barrier{

    private final int threadNumber;

    public Barrier(int pThreadNumber){
        this.threadNumber = pThreadNumber;
    }

    public synchronized void barrier(){
        wait();
    }

    public synchronized void releaseBarrier(){
        notifyAll();
    }

    public synchronized void releaseThread(){
        notify();
    }
}

But I don't really understand how to achieve that a certain number of threads are stopped until all threads arrived. Is it pos开发者_StackOverflowsible to implement a barrier using only wait/notify/notify all?


Sort of homework, so I am only giving a hint:

You want all threads to proceed when threadNumber threads are waiting. That's equivalent to the first threadNumber - 1 threads waiting for the threadNumber-th thread to arrive. One way is to count the number of threads, and do something special once the threadNumber-th thread arrives.


An additional hint that is related to a Java detail: a thread that is blocked on a wait() can be woken up spuriously; see the Object.wait() javadocs.

To tolerate spurious wakeups, you need to have a while loop where simple logic demands only an if check or a blind wait().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜