File tree 1 file changed +36
-45
lines changed 1 file changed +36
-45
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .concurrent .atomic .AtomicInteger ;
2
+
1
3
class Foo {
2
-
3
- private int counter = 1 ;
4
- private String mutex = "" ;
5
- public Foo () {
6
-
7
- }
8
4
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 ();
22
20
}
21
+ }
23
22
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 ();
37
32
}
33
+ }
38
34
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 ();
52
42
}
43
+ }
53
44
}
You can’t perform that action at this time.
0 commit comments