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
Синхронизация с Phaser в Java ⇐ JAVA
Программисты JAVA общаются здесь
1727405113
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79025620/synchronization-with-phaser-in-java[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия