Код: Выделить всё
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FooRunner {
public static void main(String[] args) {
Foo foo = new Foo();
ExecutorService executors = Executors.newFixedThreadPool(3);
Runnable first =
() -> {
try {
foo.first(() -> System.out.println("first"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
Runnable second =
() -> {
try {
foo.second(() -> System.out.println("second"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
Runnable third =
() -> {
try {
foo.third(() -> System.out.println("third"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
executors.submit(third);
executors.submit(first);
executors.submit(second);
executors.shutdown();
}
}
Код: Выделить всё
import java.util.concurrent.Phaser;
public class Foo {
private final Phaser phaser = new Phaser(1);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
phaser.arriveAndAwaitAdvance();
}
public void second(Runnable printSecond) throws InterruptedException {
phaser.awaitAdvance(1); // wait for first to complete
printSecond.run();
phaser.arriveAndAwaitAdvance();
}
public void third(Runnable printThird) throws InterruptedException {
phaser.awaitAdvance(2); // wait for second to complete
printThird.run();
phaser.arriveAndAwaitAdvance();
}
}
Код: Выделить всё
first
second
third
Подробнее здесь: https://stackoverflow.com/questions/790 ... er-in-java