JAVA如何让多个线程顺序执行?

本文探讨了三种执行多线程的方式:使用`newSingleThreadExecutor()`、在主线程中调用`join()`以及在独立线程中调用`join()`。通过实例展示了如何顺序执行线程并强调了不同方法的优劣和应用场景。
摘要由CSDN通过智能技术生成

1、使用join
2、使用newSingleThreadExecutor()
代码:

/**
 * 顺序执行多线程
 * @author GaoYuan
 */
public class SortThread {
 
    public static void main(String[] args) throws Exception{
        /**
         * 方法一
         * 利用newSingleThreadExecutor()
         */
        Thread thread1 = new Thread(() -> System.out.println("run thread1"),"thread1");
        Thread thread2 = new Thread(() -> System.out.println("run thread2"),"thread2");
        Thread thread3 = new Thread(() -> System.out.println("run thread3"),"thread3");
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(thread1);
        executor.execute(thread2);
        executor.execute(thread3);
        // 记得关闭 - 有兴趣可以看看 shutdown 与 shutdownNow 的区别
        executor.shutdown();
 
        Thread.sleep(1000);
 
        /**
         * 方法二
         * 利用thread.join 主程序中调用join
         */
        thread1.start();
        try{ thread1.join();}catch (InterruptedException e){}
        thread2.start();
        try{ thread2.join();}catch (InterruptedException e){}
        thread3.start();
 
        Thread.sleep(1000);
 
        /**
         * 方法三
         * 利用thread.join 每个独立的线程中调用
         */
        Thread thread4 = new Thread(() -> {
            System.out.println("run thread4");
            // 这里延时是为了验证thread5是否在等待thread4运行结束
            try { Thread.sleep(500); }catch (Exception e){}
        },"thread4");
        Thread thread5 = new Thread(() -> {
            try {
                // 等线程 thread4 调用结束后继续
                thread4.join();
            }catch (InterruptedException e){}
            System.out.println("run thread5");
        },"thread5");
        Thread thread6 = new Thread(() -> {
            try {
                thread5.join();
            }catch (InterruptedException e){}
            System.out.println("run thread6");
        },"thread6");
 
        thread4.start();
        thread5.start();
        thread6.start();
    }   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值