3

I'm writing a thread process using semaphores.

Given K, I want to be able to check if all previous threads have entered the critical section at least K-1 times. If not, the current thread would block until the previous threads have been able to do so.

Example: if you set K = 3, when the current thread wants to enter the critical section, it must check if all previous threads have entered the critical section K-1 (so twice in this case) times before it can enter the critical section

Does anyone know of a way in which I can implement this in Java? Thanks in advance.

4

1 回答 1

7

Make sure you are using Java 7 and use a Phaser. The Phaser accomplishes this out of the box, where K-1 will be the phase.

Here is an example:

int waitForPhase = K-1;
ExecutorService e = Executors.newFixedThreadPool(n);
Phaser phaser = new Phaser(n);
for(int i=0; i< n ;i++){
   e.submit(new Runnable(){
       public void run(){
          for(j =0 ;j < waitForPhase ; j++){ 
              //do work
              phaser.arriveAndAwaitAdvance();
              // if you do not want all sub threads to wait for each
              // this can also be phaser.arrive() 
          }
       }
   });
}
phaser.awaitAdvance(waitForPhase);

So when starting there will be n registered parties in the phaser. Each time one thread arriveAndAwaitAdvance it will wait until all threads reach that barrier. Once all threads reach that barrier the phase will increment. Once the phase reaches K-1 the invoking thread will break out.

After phaser.awaitAdvance(waitForPhase); your last statement is satisfied

current thread would block until the previous threads have been able to do so

Edit:

awaitAdvance(int phase) will suspend the current thread until the Phaser's current phase is the phase passed in as the argument. Once all threads arrived and increments to the phase number passed in the current thread will be signaled to awake.

于 2012-04-23T18:17:03.427 回答