Можно ли каким-либо образом контролировать порядок, в котором потоки должны возобновлять свою работу после завершения циклического барьера "Действие барьера"?
Ниже приведен пример, который я пробовал, но порядок последних 2 операторов сохраняетсяменяется, но я не хочу, чтобы это произошло. Это всегда должно быть: -
Thread 2 has crossed the barrier
Thread 1 has crossed the barrier
Код: -
public class CyclicBarrierExample {
private static class Task1 implements Runnable {
private CyclicBarrier barrier;
public Task1(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (InterruptedException | BrokenBarrierException ex) {
System.out.println("Exception occured");
}
}
}
private static class Task2 implements Runnable {
private CyclicBarrier barrier;
public Task2(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (InterruptedException | BrokenBarrierException ex) {
System.out.println("Exception occured");
}
}
}
public static void main(String args[]) throws InterruptedException {
final CyclicBarrier cb = new CyclicBarrier(2, ()->{
//This task will be executed once all thread reaches barrier
System.out.println("All parties are arrived at barrier, lets play");
});
//starting each of thread
Thread t1 = new Thread(new Task1(cb), "Thread 1");
Thread t2 = new Thread(new Task2(cb), "Thread 2");
t1.start();
t2.start();
}
}
Вывод: -
Thread 1 is waiting on barrier
Thread 2 is waiting on barrier
All parties are arrived at barrier, lets play
Thread 2 has crossed the barrier
Thread 1 has crossed the barrier