多线程-控制线程的执行顺序

控制线程的执行顺序的两种方法

方法一:

利用Thread.join()的方法实现,其原理是,让其父线程等待子线程执行完再执行

package com.itheima.a_demo.thread;

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

public class ThreadDemo1 {

    //线程1
    static Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread111111111111111111111111111");
        }
    });

    //线程2
    static Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread22222222222222222222222222");
        }
    });

    /**
     * 如何控制这个执行顺序?
     *      1) 通过线程的join方法来实现
     */
    public static void main(String[] args) throws InterruptedException {
        thread1.start();
        thread1.join();// 让主线程阻塞,然后让thread1 执行完之后,才执行主线程
        thread2.start();
        thread2.join();//让主线程阻塞,然后让thread2 执行完之后,才执行主线程
    }
}

部分源码
进入了join()方法,然后再进入join(0)方法

public final void join() throws InterruptedException {
        join(0);
    }

可以看到当millis = 0 的时候,执行wati(0)方法让主线程阻塞。

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

方法二:

使用static ExecutorService es = Executors.newSingleThreadExecutor()的submit方法执行线程任务

package com.itheima.a_demo.thread;

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

public class ThreadDemo2 {

    //线程1
    static Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread111111111111111111111111111");
        }
    });

    //线程2
    static Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread22222222222222222222222222");
        }
    });

    //线程3
    static Thread thread3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread33333333333333333333333333");
        }
    });

    /**
     * 如何控制这个执行顺序?
     *      1) 通过线程的join方法来实现
     *      2) 通过ExecutorService来实现
     *
     */
    //实例化一个 ExecutorService
    static ExecutorService es = Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws InterruptedException {
        es.submit(thread1);
        es.submit(thread2);
        es.submit(thread3);
        es.shutdown();
    }
}

进入Executors.newSingleThreadExecutor();的源码

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

内部实现的是一个数量为1的线程池,这样就可以控制线程的执行顺序了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值