2014-10-05 102 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. ");