一:题目
题目地址
题目说白了就是有序打印
二:思路
多线程有序打印,说白了就是让那个线程间通讯,那么我们有多种思路可以实现:
- 使用Java中的信号量”Semaphore”
- 使用Java中的CountDownLatch
- 使用Java中的原子操作类AtomicBoolean
三:代码
使用Semaphore实现
class Foo {
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
printThird.run();
}
}
使用CountDownLatch实现
class Foo {
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
printThird.run();
}
}
使用原子操作类实现
class Foo {
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
printThird.run();
}
}
测试用例
因为题目设计的比较抽象。所以自己做一下测试用例
public class PrintInOrder {
public static void main(String[] args) {
}
}