控制两个线程的启动顺序
Posted evasean
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了控制两个线程的启动顺序相关的知识,希望对你有一定的参考价值。
面试中碰到这样一道题:有线程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 block 15 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 block 14 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 }
以上是关于控制两个线程的启动顺序的主要内容,如果未能解决你的问题,请参考以下文章
newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段