如何控制多线程执行顺序

Posted zrui-xyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何控制多线程执行顺序相关的知识,希望对你有一定的参考价值。

package com.thread;

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

/**
 * 如何控制多线程执行顺序 
 * 1、join方法,让主线程等待子线程执行完后再执行
 * 2、newSingleThreadExecutor,创建执行单个任务的线程池执行、保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
 */
public class ThreadFIFO {

    public static void main(String[] args) {
        thread1();
        thread2();
    }

    public static void thread2() {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread1");

            }
        });
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread2");

            }
        });
        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread3");

            }
        });
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(thread1);
        executorService.submit(thread2);
        executorService.submit(thread3);
        executorService.shutdown();
    }

    public static void thread1() {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread1");

            }
        });
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread2");

            }
        });
        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("thread3");

            }
        });
        try {
            // join 让主线程等待子线程执行完后再执行
            thread1.start();
            thread1.join();
            thread2.start();
            thread2.join();
            thread3.start();
            thread3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

以上是关于如何控制多线程执行顺序的主要内容,如果未能解决你的问题,请参考以下文章

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

MySQL系列:kafka停止命令

硬核!管理mysql数据库的工具

java开发的项目案例,大厂内部资料

Java进阶之光!2021必看-Java高级面试题总结

控制多线程执行顺序