码迷,mamicode.com
首页 > 编程语言 > 详细

如何控制多线程执行顺序

时间:2019-05-15 12:32:14      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:catch   .exe   ack   执行顺序   exec   thread   start   join()   div   

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

 

如何控制多线程执行顺序

标签:catch   .exe   ack   执行顺序   exec   thread   start   join()   div   

原文地址:https://www.cnblogs.com/zrui-xyu/p/10868593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!