控制两个线程的启动顺序
面试中碰到这样一道题:有线程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(); } }
相关推荐
ErixHao 2020-05-30
ALiDan 2020-04-16
王道革 2020-04-11
sunzxh 2020-03-23
付春杰Blog 2020-02-17
spb 2020-02-01
xzkjgw 2020-01-17
abdstime 2020-01-17
Cheetahcubs 2020-01-04
zhujiangtaotaise 2019-12-26
zhangxiaocc 2019-11-07
Wisher 2017-06-07
思捻如枫 2019-07-01
leys 2019-07-01
讨厌什么变成什么 2019-06-30
浪里xiao白龙 2019-06-28
mojianc 2019-06-28
liwenbocsu 2019-06-28
了缺 2019-06-28