一:题目

题目地址
题目说白了就是有序打印

二:思路

多线程有序打印,说白了就是让那个线程间通讯,那么我们有多种思路可以实现:

  • 使用Java中的信号量”Semaphore”
  • 使用Java中的CountDownLatch
  • 使用Java中的原子操作类AtomicBoolean

三:代码

使用Semaphore实现

  1. class Foo {
  2. public Foo() {
  3. }
  4. public void first(Runnable printFirst) throws InterruptedException {
  5. printFirst.run();
  6. }
  7. public void second(Runnable printSecond) throws InterruptedException {
  8. printSecond.run();
  9. }
  10. public void third(Runnable printThird) throws InterruptedException {
  11. printThird.run();
  12. }
  13. }

使用CountDownLatch实现

  1. class Foo {
  2. public Foo() {
  3. }
  4. public void first(Runnable printFirst) throws InterruptedException {
  5. printFirst.run();
  6. }
  7. public void second(Runnable printSecond) throws InterruptedException {
  8. printSecond.run();
  9. }
  10. public void third(Runnable printThird) throws InterruptedException {
  11. printThird.run();
  12. }
  13. }

使用原子操作类实现

  1. class Foo {
  2. public Foo() {
  3. }
  4. public void first(Runnable printFirst) throws InterruptedException {
  5. printFirst.run();
  6. }
  7. public void second(Runnable printSecond) throws InterruptedException {
  8. printSecond.run();
  9. }
  10. public void third(Runnable printThird) throws InterruptedException {
  11. printThird.run();
  12. }
  13. }

测试用例

因为题目设计的比较抽象。所以自己做一下测试用例

  1. public class PrintInOrder {
  2. public static void main(String[] args) {
  3. }
  4. }