LeetCode 1115 交叉打印FooBar 附java代码
程序员文章站
2024-02-28 13:16:28
...
题目要求: 输入N,有两个线程,一个打印foo,一个打印bar 然后输出N个foobar。
代码如下:
class FooBar {
private int n;
private AtomicInteger value = new AtomicInteger(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; ) {
synchronized (value) {
if (value.get() %2 ==0) {
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
i++;
value.getAndIncrement();
value.notify();
} else {
value.wait();
}
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; ) {
synchronized (value) {
// printBar.run() outputs "bar". Do not change or remove this line.
if (value.get() %2 !=0) {
printBar.run();
i++;
value.getAndIncrement();
value.notify();
}else {
value.wait();
}
}
}
}
}
第二种 用semaphore信号量
信号量就是限制一个方法中同时进行线程的个数
public class Problem1115 {
private int n;
private static Semaphore semaphore1 = new Semaphore(1);
private static Semaphore semaphore2 = new Semaphore(0);
public Problem1115(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
semaphore1.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
semaphore2.release();
}
public void bar(Runnable printBar) throws InterruptedException {
// printBar.run() outputs "bar". Do not change or remove this line.
semaphore2.acquire();
printBar.run();
semaphore1.release();
}
}