class FooBar {
private int n;
private int flag = 0;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (this) {
if (flag == 0) {
printFoo.run();
flag = 1;
this.notify();
} else {
this.wait();
i--;
}
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (this) {
if (flag == 1) {
printBar.run();
flag = 0;
this.notify();
} else {
this.wait();
i--;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
FooBar fooBar = new FooBar(3);
Thread t1 = new Thread(() -> {
try {
fooBar.foo(() -> System.out.print("foo"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
fooBar.bar(() -> System.out.print("bar"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t2.start();
t1.start();
}
}
多线程力扣题解 1 https://leetcode-cn.com/problems/print-foobar-alternately/
猜你喜欢
转载自blog.csdn.net/now19930616/article/details/108588014
今日推荐
周排行