Прежде всего я создаю класс, который будет имеет конструктор и принимать классы CountDownLatch и CyclicBarrier
public static class Runner1 implements Runnable {
private final String name;
private final int ID;
public Runner1 (String name, int ID){
this.name = name;
this.ID = ID;
}
public void run (){
try{
latch.countDown();
latch.await(); // Ждем, пока все потоки будут запущены.
while (!Thread.interrupted()){
// Просто небольшая иструкция, которая просто закольцована
// и каждый раз поток встает на воображаемую линию и ждет, пока все остальные
// Встанут на этуже линию.
System.out.println (this + " on the line!");
barrier.await();
System.out.println (this + " works");
int time = rand.nextInt(5);
System.out.println (this + " will sleep for " + time); // Случайно-сгенерированная задержка.
TimeUnit.SECONDS.sleep(time);
}
} catch (InterruptedException e){
System.out.println (this + " interrupted!");
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String toString (){
return "Name: " + this.name + "# " + this.ID;
}
}
После чего я создаю основной класс, и запускаю несколько потоков.
public class MyClass {
private static final CountDownLatch latch = new CountDownLatch (3);
private static final CyclicBarrier barrier = new CyclicBarrier (3, new INFO ());
private static final Random rand = new Random ();
private static final ExecutorService exec = Executors.newCachedThreadPool();
public static void main (String [] args) throws InterruptedException {
exec.execute(new Runner1 ("Thread1", 1));
exec.execute(new Runner2 ("Thread2", 2));
exec.execute(new Runner3 ("Thread3", 3));
TimeUnit.SECONDS.sleep(10);
exec.shutdownNow();
}
}
Но на выходе, потоки работают последовательно, а не параллельно, в чем причина такой работы?
Выход:
Name: Thread1# 1 on the line!
Name: Thread2# 2 on the line!
Name: Thread3# 3 on the line!
=========
Name: Thread1# 1 works
Name: Thread1# 1 will sleep for 2
Name: Thread2# 2 works
Name: Thread2# 2 will sleep for 4
Name: Thread3# 3 works
Name: Thread3# 3 will sleep for 0
Name: Thread3# 3 on the line!
Name: Thread1# 1 on the line!
Name: Thread2# 2 on the line!
=========
Name: Thread2# 2 works
Name: Thread2# 2 will sleep for 1
Name: Thread3# 3 works
Name: Thread3# 3 will sleep for 4
Name: Thread1# 1 works
Name: Thread1# 1 will sleep for 4
Name: Thread2# 2 on the line!
Name: Thread3# 3 on the line!
Name: Thread1# 1 on the line!
=========
Name: Thread1# 1 works
Name: Thread1# 1 will sleep for 4
Name: Thread2# 2 works
Name: Thread3# 3 works
Name: Thread3# 3 will sleep for 0
Name: Thread3# 3 on the line!
Name: Thread2# 2 will sleep for 3
Name: Thread3# 3 interrupted!
Name: Thread1# 1 interrupted!
Name: Thread2# 2 interrupted!
Что я делаю не так?