-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRobot1.java
More file actions
47 lines (39 loc) · 1.6 KB
/
Robot1.java
File metadata and controls
47 lines (39 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package org.example;
/**
* Более классический вариант решения с помощью wait() и notify()
*/
public class Robot1 implements Runnable {
private final Object lock = new Object();
private boolean isRightLegTurn = true;
public void run() {
while (true) {
synchronized (lock) {
// Определяем, какая нога должна шагать
while ((isRightLegTurn && Thread.currentThread().getName().equals("Левая нога")) ||
(!isRightLegTurn && Thread.currentThread().getName().equals("Правая нога"))) {
try {
lock.wait(); // Ожидаем своего хода
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Восстановление прерывания
}
}
// Шагаем
System.out.println(Thread.currentThread().getName());
isRightLegTurn = !isRightLegTurn; // Меняем ногу
lock.notifyAll(); // Уведомляем другие потоки
}
try {
Thread.sleep(3000); // Задержка для имитации шага
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Восстановление прерывания
}
}
}
public static void main(String[] args) {
Robot1 robot1 = new Robot1();
Thread rightLegThread = new Thread(robot1, "Правая нога");
Thread leftLegThread = new Thread(robot1, "Левая нога");
rightLegThread.start();
leftLegThread.start();
}
}