java線程一直是一個比較容易困擾的地方,很多初學者都不是很清楚,
在此,我用了幾個小實驗,來將其基本概念說明一下,首先把run(),start()區分開來,
看看為什麼直接調用run()和用start()啟動一個線程的差別
1.
package com.dragon;
import java.lang.Thread;
public class ThreadTest extends Thread {
public void run() {
for(int i=0;i<10;i++){
System.out.println("this is a Thread test");
}
}
public static void main(String[] args) {
try {
Thread t = new ThreadTest();
t.run();
System.out.println("main thread is over");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
輸出結果:
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
main thread is over
表明,run()和其他方法的調用沒任何不同,main方法按順序執行了它,並列印出最後一句,
退出程式.下面看看把調用改為start()
2.
package com.dragon;
import java.lang.Thread;
public class ThreadTest extends Thread {
public void run() {
for(int i=0;i<10;i++){
System.out.println("this is a Thread test");
}
}
public static void main(String[] args) {
try {
Thread t = new ThreadTest();
t.start();
System.out.println("main thread is over");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
輸出結果:
main thread is over
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
這表明,start()方法重新建立了一個線程,在main方法執行結束後,由於start()方法建立的
線程沒有運行結束,因此主線程未能退出,直到線程 t 也執行完畢,這裡要注意,預設建立的
線程是使用者線程(非守護線程),再改一下代碼
3.
package com.dragon;
import java.lang.Thread;
public class ThreadTest extends Thread {
public void run() {
for(int i=0;i<10;i++){
System.out.println("this is a Thread test");
}
}
public static void main(String[] args) {
try {
Thread t = new ThreadTest();
t.setDaemon(true);
t.start();
System.out.println("main thread is over");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
輸出為:
main thread is over
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
為什麼沒有列印出十句呢,因為我們將 t 線程設定為了daemon(守護)線程,
程式中只有守護線程存在的時候,是可以退出的,所以只列印了七句便退出了.
再改一下代碼
4.
package com.dragon;
import java.lang.Thread;
public class ThreadTest extends Thread {
public void run() {
for(int i=0;i<100;i++){
System.out.println("this is a Thread test");
}
}
public static void main(String[] args) {
try {
Thread t = new ThreadTest();
t.start();
System.out.println("main thread is over");
System.exit(0);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
main thread is over
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
this is a Thread test
結果可見,使用者線程可以被System.exit(0)強制kill掉,所以也只列印出七句.