2014-10-05 100 views
-4

为什么下面的代码抛出异常?两次调用启动方法

class MyThread extends Thread 
{ 
    public static void main (String [] args) 
    { 
     MyThread t = new MyThread(); 
     t.start(); 
     System.out.print("one. "); 
     t.start(); 
     System.out.print("two. "); 
    } 

    public void run() 
    { 
     System.out.print("Thread "); 
    } 
} 

你能指出我出到JLS

+2

懒惰的问题。阅读javadoc。 – 2014-10-05 13:21:18

回答

1

这就是start()法的合同:

public void start() 

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. 

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method). 

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. 

Throws: 
    IllegalThreadStateException - if the thread was already started. 

您不能启动一个线程两次。

+0

+1为规范性参考。 – 2014-10-05 13:00:24

1

正如其他答案所述,您无法两次启动线程。但是,也许你想要做的是启动2个线程:在这种情况下,只是再次instanciate你的线程对象:

MyThread t = new MyThread(); 
    t.start(); 
    System.out.print("one. "); 
    MyThread t2 = new MyThread(); 
    t2.start(); 
    System.out.print("two. ");