题目描述
相关标签
相关企业
给你一个类:
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”);
}
}
}
两个不同的线程将会共用一个 FooBar 实例:
线程 A 将会调用 foo() 方法,而
线程 B 将会调用 bar() 方法
请设计修改程序,以确保 “foobar” 被输出 n 次。
示例 1:
输入:n = 1
输出:“foobar”
解释:这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,“foobar” 将被输出一次。
示例 2:
输入:n = 2
输出:“foobarfoobar”
解释:“foobar” 将被输出两次。
提示:
1 <= n <= 1000
解题思路
可以使用同步信号量的奇偶来来实现交替打印
代码实现
class FooBar {private int n;private volatile int s = 0;public FooBar(int n) {this.n = n;}public void foo(Runnable printFoo) throws InterruptedException {for (int i = 0; i < n; i++) {while (s%2!=0) {}printFoo.run();s+=1;}}public void bar(Runnable printBar) throws InterruptedException {for (int i = 0; i < n; i++) {while (s%2==0) {}// printBar.run() outputs "bar". Do not change or remove this line.printBar.run();s+=1;}}
}
测试方法
public static void main(String[] args) throws InterruptedException {FooBar foo = new FooBar(3);ExecutorService executorService = Executors.newFixedThreadPool(3);executorService.submit(() -> {try {foo.foo(() -> System.out.print("foo"));} catch (InterruptedException e) {e.printStackTrace();}});executorService.submit(()->{try {foo.bar(()->System.out.print("bar"));}catch (InterruptedException e) {e.printStackTrace();}});//匿名内部类写法//lambda表达式写法executorService.shutdown();}