首页 > 编程语言 > 详细

如何让线程按顺序执行

时间:2021-01-22 22:42:15      阅读:39      评论:0      收藏:0      [点我收藏+]

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();
    }
    
}

如何让线程按顺序执行

原文:https://www.cnblogs.com/Nilekai/p/14315081.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!