先從一個簡單的程序看起:
使用start():
public class ThreadTest {
private static void attack(){
System.out.println("fight");
System.out.println("current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
attack();
}
};
System.out.println("current main thread is:" + Thread.currentThread().getName());
thread.start();
}
}
可以看出線程被切換了不是主線程去執行非main的方法。
使用run()方法:
public class ThreadTest {
private static void attack(){
System.out.println("fight");
System.out.println("current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
attack();
}
};
System.out.println("current main thread is:" + Thread.currentThread().getName());
thread.run();
}
}
輸出結果爲:
從結果可以看出不管是主線程還是其他的線程方法,在run方法下執行的線程都是用主線程去執行。
原理如下:
- 調用start()方法會創建一個新的子線程並啓動;
- run()方法只是Thread的一個普通方法的調用。