你必須使用java.util.concurrent中,像這樣:
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
public class RendezVous extends Thread {
private final CountDownLatch _start;
private final CyclicBarrier _rdv;
private final CountDownLatch _stop;
public RendezVous(
String name,
CountDownLatch start,
CyclicBarrier rdv,
CountDownLatch stop )
{
super(name);
_start = start;
_rdv = rdv;
_stop = stop;
start();
}
@Override
public void run() {
final Random rnd = new Random(System.currentTimeMillis());
try {
System.out.println(getName() + " is started");
_start.countDown();
System.out.println(getName() + " waits for others");
_start.await();
System.out.println(getName() + " is running");
for(int count = 0, i = 0; i < 10; ++i, ++count) {
final long sleepTimer = rnd.nextInt(1000) + 1;
sleep(sleepTimer);
System.out.println(getName() +" is on his " + count + " lap");
_rdv.await();
}
_stop.countDown();
_stop.await();
System.out.println(getName() + " completes the race");
}
catch(final Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
final CountDownLatch start = new CountDownLatch(4);
final CyclicBarrier rdv = new CyclicBarrier(4);
final CountDownLatch stop = new CountDownLatch(4);
new RendezVous("STAR" , start, rdv, stop);
new RendezVous("ELEFANT", start, rdv, stop);
new RendezVous("PIGGY" , start, rdv, stop);
new RendezVous("DUCK" , start, rdv, stop);
}
}
執行日誌:
DUCK is started
STAR is started
DUCK waits for others
PIGGY is started
ELEFANT is started
PIGGY waits for others
STAR waits for others
PIGGY is running
STAR is running
ELEFANT waits for others
DUCK is running
ELEFANT is running
STAR is on his 0 lap
PIGGY is on his 0 lap
DUCK is on his 0 lap
ELEFANT is on his 0 lap
DUCK is on his 1 lap
STAR is on his 1 lap
ELEFANT is on his 1 lap
PIGGY is on his 1 lap
STAR is on his 2 lap
ELEFANT is on his 2 lap
PIGGY is on his 2 lap
DUCK is on his 2 lap
STAR is on his 3 lap
PIGGY is on his 3 lap
ELEFANT is on his 3 lap
DUCK is on his 3 lap
DUCK is on his 4 lap
PIGGY is on his 4 lap
ELEFANT is on his 4 lap
STAR is on his 4 lap
STAR is on his 5 lap
PIGGY is on his 5 lap
ELEFANT is on his 5 lap
DUCK is on his 5 lap
STAR is on his 6 lap
DUCK is on his 6 lap
PIGGY is on his 6 lap
ELEFANT is on his 6 lap
PIGGY is on his 7 lap
ELEFANT is on his 7 lap
STAR is on his 7 lap
DUCK is on his 7 lap
ELEFANT is on his 8 lap
DUCK is on his 8 lap
PIGGY is on his 8 lap
STAR is on his 8 lap
STAR is on his 9 lap
ELEFANT is on his 9 lap
DUCK is on his 9 lap
PIGGY is on his 9 lap
DUCK completes the race
PIGGY completes the race
ELEFANT completes the race
STAR completes the race
你能請更具體一點。你有什麼問題?你目前的成果是什麼?線程必須以什麼方式「跟隨並等待」彼此? – GregaMohorko
@CasperFlintrup你的意思是一個線程複雜化另一個線程將啓動?我是對的 ? –
看看[Phaser](https://dzone.com/articles/java-7-understanding-phaser)。它應該幫助你。我想稍後寫一個例子 – rvit34