LeetCode-多线程-1

1115. 交替打印 FooBar

信号量

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
class FooBar {
private int n;
private Semaphore fooSem, barSem;
public FooBar(int n) {
this.n = n;
fooSem = new Semaphore(1);
barSem = new Semaphore(0);
}

public void foo(Runnable printFoo) throws InterruptedException {

for (int i = 0; i < n; i++) {

// printFoo.run() outputs "foo". Do not change or remove this line.
fooSem.acquire();
printFoo.run();
barSem.release();
}
}

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {

// printBar.run() outputs "bar". Do not change or remove this line.
barSem.acquire();
printBar.run();
fooSem.release();
}
}
}

条件变量

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
class FooBar {
private int n;
Lock lock;
Condition condition;
boolean fooOrBar = true;
public FooBar(int n) {
this.n = n;
lock = new ReentrantLock();
condition = lock.newCondition();
}

public void foo(Runnable printFoo) throws InterruptedException {

for (int i = 0; i < n; i++) {

// printFoo.run() outputs "foo". Do not change or remove this line.
lock.lock();
while(!fooOrBar) {
condition.await();
}
printFoo.run();
fooOrBar = !fooOrBar;
condition.signalAll();
lock.unlock();
}
}

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {

// printBar.run() outputs "bar". Do not change or remove this line.
lock.lock();
while(fooOrBar) {
condition.await();
}
printBar.run();
fooOrBar = !fooOrBar;
condition.signalAll();
lock.unlock();
}
}
}

1116. 打印零与奇偶数

阅读更多