zoukankan      html  css  js  c++  java
  • 如何控制多线程执行顺序

    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();
            }
        }
    }
  • 相关阅读:
    GKB版本与UTF-8版本有什么区别(转载)
    如何与项目开发方对接
    php查询数据集的几种方式(mysql_unbuffered_query()与mysql_query()的区别)
    怎么去执行文件读写 ?
    Python中(集合、元祖、字典)等词汇基本语法
    Python入门~list 相关语法
    Python入门-基础语法实践
    newman + postman 环境搭建
    萌新驾到,请多多关照!
    切片、非空即真
  • 原文地址:https://www.cnblogs.com/zrui-xyu/p/10868593.html
Copyright © 2011-2022 走看看