2012年7月27日 星期五

Thread run() called twice

public class Hello implements Runnable {
    
public void run() {
        System.out.print("running");
    }

    
public static void main(String[] args) {
        Thread t = 
new Thread(new Test());
        t.run();
        t.run();
        t.start();
    }
}



會發生啥事?
A. Compilation fails. 
B. An exception is thrown at runtime
C. The code executes and prints "running" 
D. The code executes and prints "runningrunning" 
E. The code executes and prints "runningrunningrunning" 






A: E


t.run(); 是使用一般函式呼叫,不管呼叫幾次都可以
t.start(); 
是透過Thread 本身的功能來呼叫run() 同時只能呼叫一次
一個執行緒只能Start 一次,就像一個火箭只能發射一次


如果程式碼是這樣寫:
t.run();
t.start();
t.start();
那麼就會出現java.lang.IllegalThreadStateException



資料來源:
http://yaya741228.pixnet.net/blog/post/78949696-%E4%B8%80%E5%A4%A9%E4%BA%94%E9%A1%8Cscjp(11~15)

沒有留言:

張貼留言