题型:多线程
难度系数:简单
题目:有三个目标方法,用于打印出不同的结果。现提供三个线程,分别执行不同的方法,需按一定的顺序执行这三个方法。
示例:
1、
输入: [1,2,3]
输出: "onetwothree"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。2、
输入: [1,3,2]
输出: "onetwothree"
解释:
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。
无论方法如何分配执行,结果都是onetwothree
解决此类问题有多种方式,主要涉及内容为多线程间的通信。利用信号量或者CountDownLatch、CyclicBarrier等都可以
这里主要介绍信号量和CountDownLatch
1、利用Semaphore
需要注意的是semaphore的permit得设为0,并且在第一个需要执行的方法中添加release()。
class Foo {
public Semaphore seam_two = new Semaphore(0);
public Semaphore seam_three = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
seam_two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
seam_two.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
seam_three.release();
}
public void third(Runnable printThird) throws InterruptedException {
seam_three.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
2、利用CountDownLatch
class Foo {
//public Semaphore seam_two = new Semaphore(0);
//public Semaphore seam_three = new Semaphore(0);
public CountDownLatch countDownLatch1 = new CountDownLatch(1);
public CountDownLatch countDownLatch2 = new CountDownLatch(1);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
//seam_two.release();
countDownLatch1.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
countDownLatch1.await();
//seam_two.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
//seam_three.release();
countDownLatch2.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
countDownLatch2.await();
//seam_three.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
实现思路基本上一样,都是控制线程等待和唤醒来控制方法的执行顺序。