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

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

直接代码说明

/**
 * 顺序执行多线程
 * @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();
    }   
}

博客

https://my.oschina.net/gmarshal/blog/1926624

欢迎关注我的个人微信订阅号:(据说这个头像程序猿专用)

输入图片说明

转载于:https://my.oschina.net/gmarshal/blog/1926624

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值