如何控制多线程执行顺序?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzti_erlie/article/details/84926355

介绍

方法1

通过join方法去保证多线程顺序执行
join:让主线程等待子结束以后才能继续运行

方法2

ExecutorService executorService = Executors.newSingleThreadExecutor();

FIFO队列

代码

public class Test {

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

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

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

    static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws InterruptedException {

        // thread1
        // thread2
        // thread3
        method1();

        // thread1
        // thread2
        // thread3
        method2();

    }

    private static void method2() throws InterruptedException {
        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();
        thread3.start();
    }

    private static void method1() {
        executorService.submit(thread1);
        executorService.submit(thread2);
        executorService.submit(thread3);
    }

}

参考博客

猜你喜欢

转载自blog.csdn.net/zzti_erlie/article/details/84926355