fix: ensure thread-safe visibility in livelock example
This commit is contained in:
@@ -13,14 +13,18 @@ public class LiveLock {
|
||||
currentPerson = person;
|
||||
}
|
||||
|
||||
public synchronized Person getPerson() {
|
||||
return currentPerson;
|
||||
}
|
||||
|
||||
public synchronized void pass() {
|
||||
System.out.printf("%s прошёл по коридору!%n", currentPerson.name);
|
||||
}
|
||||
}
|
||||
|
||||
static class Person {
|
||||
private String name;
|
||||
private boolean wantsToPass;
|
||||
private final String name;
|
||||
private volatile boolean wantsToPass;
|
||||
|
||||
public Person(String personName) {
|
||||
name = personName;
|
||||
@@ -40,11 +44,12 @@ public class LiveLock {
|
||||
|
||||
// Если сейчас право пройти принадлежит другому человеку,
|
||||
// немного ждём и снова проверяем ситуацию.
|
||||
if (corridor.currentPerson != this) {
|
||||
if (corridor.getPerson() != this) {
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
continue;
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -81,6 +86,7 @@ public class LiveLock {
|
||||
// Первый поток — Иван.
|
||||
new Thread(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ivan.walkThrough(corridor, petr);
|
||||
}
|
||||
@@ -90,6 +96,7 @@ public class LiveLock {
|
||||
// Второй поток — Пётр.
|
||||
new Thread(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
petr.walkThrough(corridor, ivan);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user