-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
1115.java
77 lines (63 loc) · 2.21 KB
/
1115.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
__________________________________________________________________________________________________
sample 15 ms submission
import java.util.concurrent.Semaphore;
class FooBar {
private int n;
private Semaphore semaFoo;
private Semaphore semaBar;
public FooBar(int n) {
this.n = n;
this.semaFoo = new Semaphore(1);
this.semaBar = new Semaphore(0);
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaFoo.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
semaBar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaBar.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
semaFoo.release();
}
}
}
__________________________________________________________________________________________________
sample 17 ms submission
import java.util.concurrent.atomic.*;
class FooBar {
final private int n;
private AtomicBoolean check = new AtomicBoolean(false);
public FooBar(int n) {
this.n = n;
}
public synchronized void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(check.get()){
wait();
}
if(check.compareAndSet(false,true))
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
if(check.compareAndSet(false,true));
notify();
}
}
public synchronized void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(!check.get()){
wait();
}
if(check.compareAndSet(true,false))
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
notify();
}
}
}
__________________________________________________________________________________________________