你的位置:首页 > Java教程

[Java教程]控制两个线程的启动顺序

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

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

1. 线程A启动3秒后

2. 线程A运行结束后

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

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

 1 public class RunA implements Runnable { 2  private CountDownLatch cdl; 3  public RunA(CountDownLatch cdl){ 4   this.cdl = cdl; 5  } 6  @Override 7  public void run() { 8   // TODO Auto-generated method stub 9   try {10    Thread.sleep(1000);11    cdl.countDown();12    System.out.println("A run over");13   } catch (InterruptedException e) {14    // TODO Auto-generated catch block15    e.printStackTrace();16   }17  }18 }

 

 1 public class RunB implements Runnable { 2  private CountDownLatch cdl; 3  public RunB(CountDownLatch cdl){ 4   this.cdl = cdl; 5  } 6  @Override 7  public void run() { 8   // TODO Auto-generated method stub 9   try {10    cdl.await(3000, TimeUnit.MILLISECONDS);11    System.out.println("B run over");12   } catch (InterruptedException e) {13    // TODO Auto-generated catch block14    e.printStackTrace();15   }16  }17 }

 

1 public class Test {2  public static void main(String[] args) {3   CountDownLatch cdl = new CountDownLatch(1);4   Thread ta = new Thread(new RunA(cdl));5   Thread tb = new Thread(new RunB(cdl));6   ta.start();7   tb.start();8  }9 }