启动线程:

  从一个最基本的面试题开始,启动线程到底是start()还是run()?

Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
Thread thread = new Thread(runnable);
thread.run();
thread.start();
结果:
main
Thread-0

  我们可以看到thread.run()是通过main线程执行的,而start()启动的才是一个新线程。run()只是在线程启动的时候进行回调而已,如果没有start(),run()也只是一个普通方法。

  start()方法不一定直接启动新线程,而是请求jvm在空闲的时候去启动,由线程调度器决定。

思考题:如果重复执行start()方法会怎样?

Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
Thread thread = new Thread(runnable);
thread.start();
thread.start();
结果:
Exception in thread "main" Thread-0
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:705)
at com.diamondshine.Thread.ThreadClass.main(ThreadClass.java:33)

重复执行start()会出现异常,可以从start()的源码得到,因为启动线程的时候,会检测当前线程状态

public synchronized void start() {
    
    if (threadStatus != 0)    //判断线程启动时的状态是否为new,如果不是,直接抛出异常
        throw new IllegalThreadStateException();

    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {

        }
    }
}
View Code

相关文章:

  • 2021-10-04
  • 2021-10-11
  • 2021-06-26
  • 2022-12-23
  • 2021-11-20
  • 2021-08-13
  • 2023-02-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2021-11-29
  • 2021-07-16
  • 2021-11-17
  • 2021-12-07
相关资源
相似解决方案