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.
我们通过同步synchronized(lock())来进行阻塞操作,用isfooPrint来标记,如果满足while循环,则锁等待,不满足while循环,则进行下一步操作,进入打印程序,改写isfooPrint的值,唤醒其他进程。
class FooBar {
private int n;
Object lock=new Object();
boolean isfooPrint;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized(lock){
while(isfooPrint==true){
lock.wait();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
isfooPrint=true;
lock.notify();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized(lock){
while(isfooPrint==false){
lock.wait();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
isfooPrint=false;
lock.notify();
}
}
}
}
也可以通过volatile关键字和其他锁机制进行结合,volatile关键字简介可参考:
https://blog.youkuaiyun.com/liuwenyou/article/details/100690719

本文探讨了在多线程环境中如何确保正确并发执行的方法。通过使用synchronized关键字和wait/notify机制,实现两个线程间foo和bar的交替打印,确保了线程安全和预期的输出顺序。
1226

被折叠的 条评论
为什么被折叠?



