-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathTwoLegsRobot.java
108 lines (95 loc) · 2.9 KB
/
TwoLegsRobot.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package by.andd3dfx.multithreading;
import lombok.Builder;
import lombok.SneakyThrows;
import java.io.StringWriter;
import java.util.concurrent.Semaphore;
/**
* <pre>
* Дан класс:
* class Foot implements Runnable {
* private String name;
*
* public Foot(String name) {
* this.name = name;
* }
*
* public void run() {
* for (int i = 0; i < 10; i++) {
* step();
* }
* }
*
* private void step() {
* System.out.println(name + " steps!");
* }
* }
*
* И программа:
* public class MainClass {
* public static void main(String[] args) {
* new Thread(new Foot("left")).start();
* new Thread(new Foot("right")).start();
*
* while(true);
* }
* }
*
* Исправить программу, чтобы робот шагал ногами по очереди.
* Сделать так, чтобы не потреблялись ресурсы CPU, пока ожидаем передвижения очередной ноги.
* </pre>
*
* @see <a href="https://youtu.be/MBANIKUlpEs">Video solution</a>
*/
public class TwoLegsRobot {
private Foot leftLeg;
private Foot rightLeg;
private StringWriter logWriter;
public TwoLegsRobot() {
Semaphore leftSemaphore = new Semaphore(1);
Semaphore rightSemaphore = new Semaphore(0);
logWriter = new StringWriter();
leftLeg = Foot.builder()
.name("left")
.mySemaphore(leftSemaphore)
.notMySemaphore(rightSemaphore)
.logWriter(logWriter)
.build();
rightLeg = Foot.builder()
.name("right")
.mySemaphore(rightSemaphore)
.notMySemaphore(leftSemaphore)
.logWriter(logWriter)
.build();
}
public void start() {
new Thread(leftLeg).start();
new Thread(rightLeg).start();
}
public String getLogs() {
return logWriter.toString();
}
@Builder
public static class Foot implements Runnable {
private final String name;
private final Semaphore mySemaphore;
private final Semaphore notMySemaphore;
private final StringWriter logWriter;
@SneakyThrows
public void run() {
for (int i = 0; i < 10; i++) {
step();
}
}
private void step() throws InterruptedException {
mySemaphore.acquire();
logWriter.write("%s steps!".formatted(name));
notMySemaphore.release();
}
}
public static void main(String[] args) throws InterruptedException {
var robot = new TwoLegsRobot();
robot.start();
Thread.sleep(100);
System.out.println(robot.getLogs());
}
}