多线程-线程的启动(二)

tech2025-08-10  3

线程的启动

启动线程的正确和错误方式–start()和run()的比较

public static void main(String[] args) { Runnable runnable = () -> { System.out.println(Thread.currentThread().getName()); }; runnable.run(); new Thread(runnable).start(); } //结果 main Thread-0

可以看到runnable.run是通过主线程来实现的,并没有创建新的线程,而通过start方法是通过创建新的线程的方式来实现的

思考:既然我们是通过start方法来启动线程的,那么如果我们直接多次对同一个thread类使用start方法会怎么样呢

试试

public static void main(String[] args) { Thread thread = new Thread(); thread.start(); thread.start(); } //哦吼,报错了, Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:705) at com.hd.thread.start.CantStartTwice.main(CantStartTwice.java:14)

下面我们进入到源码中看一下为啥它会报错

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(); //调用start0这个方法是nativie的,并不是用java实现的先不做研究 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 */ } } }

面试问题

一个线程两次调用start方法会出现什么情况?为什么? 会抛出非法线程状态异常,在start()方法里面,一开始就会进行启动新线程检查线程状态。

既然start方法会调用run方法,为什么我们选择调用start方法,而不是直接调用run方法呢?

因为调用start方法才是真正意义上的启动一个线程,它会去经历线程的各个生命周期,如果调用run方法,它仅仅是一个普通方法而已,并不会创建新的线程。

start的执行流程 – (1)检查线程状态 – (2)加入线程组 – (3)调用start0启动线程
最新回复(0)