为什么 Java 线程对象无法重新启动?
我知道不可能重新启动使用的Java Thread对象,但我没有找到为什么不允许这样做的解释;即使保证线程已完成(请参阅下面的示例代码)。
我不明白为什么(或者至少是一个)方法不能以某种方式将Thread对象的内部状态 ( 无论它们是什么 - 重置为它们在新创建Thread对象时具有的相同值。start()
restart()
示例代码:
class ThreadExample {
public static void main(String[] args){
Thread myThread = new Thread(){
public void run() {
for(int i=0; i<3; i++) {
try{ sleep(100); }catch(InterruptedException ie){}
System.out.print(i+", ");
}
System.out.println("done.");
}
};
myThread.start();
try{ Thread.sleep(500); }catch(InterruptedException ie){}
System.out.println("Now myThread.run() should be done.");
myThread.start(); // <-- causes java.lang.IllegalThreadStateException
} // main
} // class