Skip to content

Commit 9d3ace1

Browse files
authored
Update Print in Order.java
1 parent 9b30ec2 commit 9d3ace1

File tree

1 file changed

+36
-45
lines changed

1 file changed

+36
-45
lines changed

Concurrency/Print in Order.java

Lines changed: 36 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,44 @@
1+
import java.util.concurrent.atomic.AtomicInteger;
2+
13
class Foo {
2-
3-
private int counter = 1;
4-
private String mutex = "";
5-
public Foo() {
6-
7-
}
84

9-
public void first(Runnable printFirst) throws InterruptedException {
10-
11-
// printFirst.run() outputs "first". Do not change or remove this line.
12-
boolean flag = true;
13-
while (flag) {
14-
synchronized(mutex) {
15-
if (counter == 1) {
16-
printFirst.run();
17-
counter++;
18-
flag = false;
19-
}
20-
}
21-
}
5+
private Object lock;
6+
private AtomicInteger counter;
7+
8+
public Foo() {
9+
this.lock = new Object();
10+
this.counter = new AtomicInteger(0);
11+
}
12+
13+
public void first(Runnable printFirst) throws InterruptedException {
14+
15+
// printFirst.run() outputs "first". Do not change or remove this line.
16+
synchronized (lock) {
17+
printFirst.run();
18+
this.counter.incrementAndGet();
19+
this.lock.notifyAll();
2220
}
21+
}
2322

24-
public void second(Runnable printSecond) throws InterruptedException {
25-
26-
// printSecond.run() outputs "second". Do not change or remove this line.
27-
boolean flag = true;
28-
while (flag) {
29-
synchronized(mutex) {
30-
if (counter == 2) {
31-
printSecond.run();
32-
counter++;
33-
flag = false;
34-
}
35-
}
36-
}
23+
public void second(Runnable printSecond) throws InterruptedException {
24+
// printSecond.run() outputs "second". Do not change or remove this line.
25+
synchronized (lock) {
26+
while (this.counter.get() != 1) {
27+
this.lock.wait();
28+
}
29+
printSecond.run();
30+
this.counter.incrementAndGet();
31+
this.lock.notifyAll();
3732
}
33+
}
3834

39-
public void third(Runnable printThird) throws InterruptedException {
40-
41-
// printThird.run() outputs "third". Do not change or remove this line.
42-
boolean flag = true;
43-
while (flag) {
44-
synchronized(mutex) {
45-
if (counter == 3) {
46-
printThird.run();
47-
counter++;
48-
flag = false;
49-
}
50-
}
51-
}
35+
public void third(Runnable printThird) throws InterruptedException {
36+
// printThird.run() outputs "third". Do not change or remove this line.
37+
synchronized (lock) {
38+
while (this.counter.get() != 2) {
39+
this.lock.wait();
40+
}
41+
printThird.run();
5242
}
43+
}
5344
}

0 commit comments

Comments
 (0)