JAVA多线程启动顺序

问题描述:

预先创建了30个线程(DemoThread),循环启动(start)线程去执行方法,方法的代码上加了ReentrantLock公平锁;Windows 和 Linux 测试效果如下:

既然是按着顺序启动(start)的线程,方法的执行也加上了公平锁,结果为什么只有 Linux 是按着0-29的顺序在输出呢? 

原因分析

1、Thread.start() 和 Thread.run()

这两个方法作用就是执行线程的 run 方法中的代码,但是本质上有很大的区别。

Thread.start()源码如下:

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the <code>run</code> method of this thread.
 * <p>
 * The result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * <code>start</code> method) and the other thread (which executes its
 * <code>run</code> method).
 * <p>
 * It is never legal to start a thread more than once.
 * In particular, a thread may not be restarted once it has completed
 * execution.
 *
 * @exception  IllegalThreadStateException  if the thread was already
 *               started.
 * @see        #run()
 * @see        #stop()
 */
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

private native void start0();

start() 是一个synchronized修饰的方法,最终是调用了一个start0()native方法,此时会执行以下步骤:

  • 通过JVM告诉操作系统创建一个Thread;

  • 操作系统开辟内存,并通过创建 Thread 线程对象;

  • 操作系统对 Thread 对象进行调度,并确定执行时间;

  • Thread 在操作系统中被执行;

以上过程,主线程(main)并不需要等待 Thread 执行完毕,而是直接往后继续执行了;至于对 Thread 的调度,什么时候执行,就完全交由系统根据自己的CPU竞争策略来决定,跟主线程(main)、调用 start 方法的顺序没有任何关系了;

CPU 竞争策略

那上面的测试输出,为什么最终执行的结果看起来只有Windows乱了呢?

这是由于两个操作系统采用了不同的 CPU 竞争策略,Linux系统使用的是时间片算法,Windows则属于抢占式这两种策略最终会带来不同的线程执行顺序;

时间片算法

在时间片算法中,所有的进程排成一个队列操作系统按照他们的顺序,给每个进程分配一段时间,即该进程允许运行的时间。如果在时间片结束时进程还在运行,则CPU将被剥夺并分配给另一个进程。

如果进程在时间片结束前阻塞或结束,则CPU当即进行切换。调度程序所要做的就是维护一张就绪进程列表,当进程用完它的时间片后,它被移到队列的末尾。

抢占式操作系统

所谓抢占式操作系统,就是说如果一个进程得到了 CPU 时间,除非它自己放弃使用 CPU ,否则将完全霸占 CPU 。因此可以看出,在抢占式操作系统中,操作系统假设所有的进程都是“人品很好”的,会主动退出 CPU 。

在抢占式操作系统中,假设有若干进程,操作系统会根据他们的优先级、饥饿时间(已经多长时间没有使用过 CPU 了),给他们算出一个总的优先级来。操作系统就会把 CPU 交给总优先级最高的这个进程。

当进程执行完毕或者自己主动挂起后,操作系统就会重新计算一 次所有进程的总优先级,然后再挑一个优先级最高的把 CPU 控制权交给他。

相比下来,抢占式就有点像野蛮人;这也就解释了 Windows 为什么每次输出的结果都不太一样;由于测试用例执行的内容并不复杂,Linux 在最开始的时候,同一时间片下,就能执行完所有的指令,因此看起来就像线程是有序的在执行,当线程多导致同一时间片无法完成之后,同样也会出现错乱,但相比 Windows 更加有规律;

以下是 200 个线程的执行结果:

所以,不管是 Windows 还是 Linux,最终执行 run 方法的顺序跟线程调用start() 顺序并不是一致,不能通过 start() 方法来决定线程的执行顺序;跟 ReentrantLock 公平锁就更没有任何关系了;

Thread.run()源码如下:

/**
 * If this thread was constructed using a separate
 * <code>Runnable</code> run object, then that
 * <code>Runnable</code> object's <code>run</code> method is called;
 * otherwise, this method does nothing and returns.
 * <p>
 * Subclasses of <code>Thread</code> should override this method.
 *
 * @see     #start()
 * @see     #stop()
 * @see     #Thread(ThreadGroup, Runnable, String)
 */
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

 只有当线程创建时,传入了Runnable对象,调用此方法才会有效,而且执行的过程并不是一个异步任务,不会交给“线程规划器”来管理,是由调用 run() 方法的主线程(main)在执行;通过 Thread.run() 执行的代码,是可以保证线程的执行顺序的,但是多线程的执行过程就由并行变成了串行化,也就是说,线程1执行完在执行线程2,线程2执行完才会轮到线程3 .... 一直到最后一个线程;这样就失去了多线程的意义了,因此, Thread.run() 在实际开发中要酌情使用。

2、线程的有序执行

2.1、join()join方法Thread类中的一个方法,作用是等待该线程执行直到终止。

public class ThreadTest {
    public static void main(String[] args) throws Exception{
        Thread t1 = new Thread(()-> System.out.println(Thread.currentThread().getName()+ "线程1"));
        Thread t2 = new Thread(()-> System.out.println(Thread.currentThread().getName()+ "线程2"));
        Thread t3 = new Thread(()-> System.out.println(Thread.currentThread().getName()+ "线程3"));
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
    }
}

2.2、FutureTask,利用 get() 方法阻塞等待返回,只有执行完之后,才会继续往后执行;

public  static void futureTask() throws Exception{
    FutureTask<String> f1 = new FutureTask<>(() -> {
        System.out.println(Thread.currentThread().getName() + " FutureTask1");
        return "FutureTask1";
    });
    FutureTask<String> f2 = new FutureTask<>(() -> {
        System.out.println(Thread.currentThread().getName() + " FutureTask2");
        return "FutureTask2";
    });
    FutureTask<String> f3 = new FutureTask<>(() -> {
        System.out.println(Thread.currentThread().getName() + " FutureTask3");
        return "FutureTask3";
    });
    Thread t1 = new Thread(f1,"线程1");
    Thread t2 = new Thread(f2,"线程2");
    Thread t3 = new Thread(f3,"线程3");
    t1.start();
    System.out.println(f1.get());
    t2.start();
    System.out.println(f2.get());
    t3.start();
    System.out.println(f3.get());
}

2.3、单线程池,单线程池同一时间只允许有一个线程在执行,因此可以将要执行的线程按顺序提交给线程池,就能实现顺序执行的效果;


public static void singleThreadExecutor() {
    ExecutorService threadPool = Executors.newSingleThreadExecutor();
    Thread t1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + " 线程1"));
    Thread t2 = new Thread(() -> System.out.println(Thread.currentThread().getName() + " 线程2"));
    Thread t3 = new Thread(() -> System.out.println(Thread.currentThread().getName() + " 线程3"));
    threadPool.execute(t1);
    threadPool.execute(t2);
    threadPool.execute(t3);
    threadPool.shutdown();
}

2.4、CountDownLatch,利用 CountDownLatch 的 await() 阻塞方法,后一个线程只有等前一个线程执行完并调用countDown(),才能继续执行;

public static void countDownLatch() {
    CountDownLatch c1 = new CountDownLatch(1);
    CountDownLatch c2 = new CountDownLatch(1);
    Thread t1 = new Thread(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 线程1 等待1000ms");
        c1.countDown();
    });

    Thread t2 = new Thread(() -> {
        try {
            c1.await();
            System.out.println(Thread.currentThread().getName() + " 线程2");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        c2.countDown();
    });

    Thread t3 = new Thread(() -> {
        try {
            c2.await();
            System.out.println(Thread.currentThread().getName() + " 线程3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    t1.start();
    t2.start();
    t3.start();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

才疏学浅的浅~

谢谢老板,老板大气^_^

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值