zoukankan      html  css  js  c++  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 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 }
  • 相关阅读:
    内联汇编的使用
    metamask注记词
    一个简单的增删改查合约
    企业邮箱账号
    压缩包管理
    设计模式
    软硬链接ln
    文件IO-Linux
    静态库和动态库
    gdb调试
  • 原文地址:https://www.cnblogs.com/evasean/p/7999582.html
Copyright © 2011-2022 走看看