-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1115.java
More file actions
72 lines (67 loc) · 1.72 KB
/
Copy path1115.java
File metadata and controls
72 lines (67 loc) · 1.72 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
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
// 1115. Print FooBar Alternately
// Suppose you are given the following code:
//
// class FooBar {
// public void foo() {
// for (int i = 0; i < n; i++) {
// print("foo");
// }
// }
//
// public void bar() {
// for (int i = 0; i < n; i++) {
// print("bar");
// }
// }
// }
// The same instance of FooBar will be passed to two different threads:
//
// thread A will call foo(), while
// thread B will call bar().
// Modify the given program to output "foobar" n times.
//
//
//
// Example 1:
//
// Input: n = 1
// Output: "foobar"
// Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
// "foobar" is being output 1 time.
// Example 2:
//
// Input: n = 2
// Output: "foobarfoobar"
// Explanation: "foobar" is being output 2 times.
//
//
// Constraints:
//
// 1 <= n <= 1000
//
// Runtime 23ms Beats 89.39%of users with Java
// Memory 43.29MB Beats 5.10%of users with Java
class FooBar {
private int n;
Semaphore semaphoreF = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreF.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
semaphoreB.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreB.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
semaphoreF.release();
}
}
}