如何控制线程执行顺序

方式一、thread.join()

package com.it.demo;

public class Demo {
    static Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t1");
        }
    });

    static Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t2");
        }
    });

    static Thread t3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t3");
        }
    });

    public static void main(String[] args) throws Exception {
        t1.start();
        t1.join();

        t2.start();
        t2.join();

        t3.start();
    }

}

原理:
thread.join()让主线程等待,当子线程执行完之后主线程在继续执行,从而实现控制线程执行顺序的目的


方式二、Executors.newSingleThreadExecutor()

package com.it.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    static ExecutorService executor = Executors.newSingleThreadExecutor();
    
    static Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t1");
        }
    });

    static Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t2");
        }
    });

    static Thread t3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("t3");
        }
    });

    public static void main(String[] args) throws Exception {
        executor.submit(t1);

        executor.submit(t2);

        executor.submit(t3);
    }

}

原理:
Executors.newSingleThreadExecutor()创建了一个只有单个线程的线程池,当使用 executor.submit()方法执行多个线程时,多余的线程会放入队列中(设计线程池底层原理),由执行器一个线程一个线程的执行,从而达到了控制线程顺序的目的

你可能感兴趣的:(多线程)