start()和run()開始的時候總是記不住那個是線程的啟動方法,現在是記得很真切了!
如果用run()啟動線程就跟不用線程效果是一樣的,因為是run是順序執行的。start()才是線程的啟動方法。做了個測試類:
用一個for循環多次,每一次都new一個線程,在構造器中分別start,run好多好多次就出現結果了(重寫了toString和super這樣結果看起來更直觀)。
其實Thread類實現了Runnable接口,run()就是接口里的方法,所以想用run就需要自己重寫這個方法。
1 public class SimpleThread extends Thread { 2 private int countDown = 5; 3 private static int threadCount = 0; 4 public SimpleThread() { 5 // Store the thread name: 6 super("第"+Integer.toString(++threadCount)+"條線程: "); 7 start(); 8 //run(); 9 } 10 public String toString() { 11 return "#########" + getName() + "執行到第" + countDown + "次 "+"#########"; 12 } 13 public void run() { 14 while(true) { 15 System.out.println(this); 16 if(--countDown == 0) 17 return; 18 } 19 } 20 public static void main(String[] args) { 21 for(int i = 0; i < 6; i++) { 22 new SimpleThread(); 23 } 24 } 25 } 26