Thread的join方法

join() :Waits for this thread to die.等待此线程结束

join(long millis): Waits at most milliseconds for this thread to die. A timeout of 0 means to wait forever.设置加入的线程超时时间,0代表永久等待

Thread类的join方法是等待join的线程结束,然后再执行自身的线程。

/**
 *假如有a、b、c三个线程安装顺序执行
 */
public class JoinTest {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("A");});
        Thread b = new Thread(() -> {
            try {
                a.join();
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B");});
        Thread c = new Thread(() -> {
            try {
                b.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("C");});

        c.start();
        b.start();
        a.start();
    }
}	

线程池

通过创建单个线程的线程池的方式,将线程放在一个队列中实现顺序执行。

public class ThreadFactoryTest {
    public static void main(String[] args) {
        ExecutorService ex = Executors.newSingleThreadExecutor();
        ex.execute(() -> System.out.println("A"));
        ex.execute(() -> System.out.println("B"));
        ex.execute(() -> System.out.println("C"));
        ex.shutdown();
    }
    
}

相关文章:

  • 2022-01-08
  • 2022-12-23
  • 2021-08-11
  • 2022-12-23
  • 2021-09-30
  • 2021-08-12
  • 2021-04-26
  • 2021-08-16
猜你喜欢
  • 2022-12-23
  • 2019-03-25
  • 2021-07-28
  • 2022-12-23
  • 2021-09-26
  • 2022-12-23
相关资源
相似解决方案