如何让线程按顺序执行

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();
    }
    
}
posted @ 2021-01-22 20:18  往事随雨  阅读(123)  评论(0)    收藏  举报