このようにあなたは、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あなたは1つのスレッドの複雑さを意味する別のスレッドが開始されますか?私は正しいですよ ? –
[Phaser](https://dzone.com/articles/java-7-understanding-phaser)を見てください。それはあなたを助けるはずです。少し遅れて例を書こうとしています – rvit34