Синхронизация с Phaser в JavaJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Синхронизация с Phaser в Java

Сообщение Anonymous »

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();
}
}

Реализация синхронизации с помощью Phaser.
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

но потоки не ждут фазера. Является ли текущая реализация неправильным использованием фазера?
Примечание: Phaser не является правильным выбором для обеспечения последовательного синхронизированного поведения между потоками.

Phaser phaser = new Phaser(4); // 3 threads + main thread

for (int i = 0; i < 3; i++) {
new Thread(
() -> {
try {
System.out.println(
"Waiting Before Phase 1 for " + Thread.currentThread().getName());
phaser.arriveAndAwaitAdvance(); // Wait for other threads

Thread.sleep(Duration.ofSeconds(10));
System.out.println("Before Phase 2 for " + Thread.currentThread().getName());
// Phase 2
phaser.arriveAndAwaitAdvance(); // Wait for next phase
} catch (Exception e) {
e.printStackTrace();
}
})
.start();
}

phaser.arriveAndDeregister(); // Deregister main thread



Подробнее здесь: https://stackoverflow.com/questions/790 ... er-in-java
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»