一个线程实例只能运行一次,即Thread.start()方法只能执行一次。看了Thread的源码,发现其中维护了一个变量started。当线程运行start()期间,首先判断started,如果为true,则抛出异常并终止运行,如果为false,则继续执行,并且将started变量置为true。源码如下:
public synchronized void start() {
if (started)
throw new IllegalThreadStateException();
started = true;
group.add(this);
start0();
}
public synchronized void start() {
if (started)
throw new IllegalThreadStateException();
started = true;
group.add(this);
start0();
}
本文详细解释了Java中线程启动机制的内部实现原理,特别是为何一个线程只能被启动一次的原因。通过分析Thread类的start()方法源码,揭示了started变量在控制线程重复启动中的关键作用。

581

被折叠的 条评论
为什么被折叠?



