# 多线程题目求助

0
[已解决问题] 解决于 2023-08-29 21:01

1115题 交替打印FooBar（https://leetcode.cn/problems/print-foobar-alternately/description/）

volatile机制下，不会指令重排序。但是仍然会卡死在while循环，大佬们有人知道为什么吗？

``````class FooBar {
private int n;

public FooBar(int n) {
this.n = n;
}
private volatile boolean flag1 = false;
private volatile boolean flag2 = true;
public void foo(Runnable printFoo) throws InterruptedException {

for (int i = 0; i < n; i++) {
while(flag1){}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag1 = true;
flag2 = false;

}
}

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {
while(flag2) {}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag2 = true;
flag1 = false;
}
}
}
``````

0

``````class FooBar {
private int n;
private boolean flag = false;

public FooBar(int n) {
this.n = n;
}

public synchronized void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while (flag) {
wait();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag = true;
notifyAll();
}
}

public synchronized void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while (!flag) {
wait();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag = false;
notifyAll();
}
}
}
``````

lanedm | 老鸟四级 |园豆：2381 | 2023-08-29 19:32

0

https://zhuanlan.zhihu.com/p/87614101

@谷峦坚:

class FooBar {
private int n;

``````private AtomicBoolean ab;

public FooBar(int n) {
this.n = n;
this.ab = new AtomicBoolean(false);
}

public void foo(Runnable printFoo) throws InterruptedException {

for (int i = 0; i < n; i++) {
while (! ab.compareAndSet(false, true)) {
// nothing
}

// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();

try {
TimeUnit.NANOSECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {
// 循环等待
while (! ab.compareAndSet(true, false)) {
// nothing
}

// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();

// 延迟
try {
TimeUnit.NANOSECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
``````

}

@快乐的凡人721: 我之前表述不清，我疑惑的是为什么我的解法不行，而不是这个问题的解法。

您需要登录以后才能回答，未注册用户请先注册