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.