控制两个线程的启动顺序

面试中碰到这样一道题:有线程A和线程B,怎样控制线程B在线程A启动3秒后或者线程A运行结束后启动?

题目说明了线程B的启动时间是要满足两个条件:

1. 线程A启动3秒后

2. 线程A运行结束后

也就是说只要上面两个条件有一个满足,线程B就要启动。

用CountDownLatch控制调用时序,代码如下:

public class RunA implements Runnable {
     private CountDownLatch cdl;
     public RunA(CountDownLatch cdl){
         this.cdl = cdl;
     }
     @Override
     public void run() {
         // TODO Auto-generated method stub
         try {
             Thread.sleep(1000);
             cdl.countDown();
             System.out.println("A run over");
         } catch (InterruptedException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
 }
public class RunB implements Runnable {
     private CountDownLatch cdl;
     public RunB(CountDownLatch cdl){
         this.cdl = cdl;
     }
     @Override
     public void run() {
         // TODO Auto-generated method stub
         try {
             cdl.await(3000, TimeUnit.MILLISECONDS);
             System.out.println("B run over");
         } catch (InterruptedException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
 }
public class Test {
     public static void main(String[] args) {
         CountDownLatch cdl = new CountDownLatch(1);
         Thread ta = new Thread(new RunA(cdl));
         Thread tb = new Thread(new RunB(cdl));
         ta.start();
         tb.start();
     }
 }

相关推荐