我們知道,我們通過調用線程的start方法啟動一個線程,那麼,我們可以直接調用run方法來啟動一個線程嗎?
先看下面一段代碼:
[java] view plain copy
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TestThread tt = new TestThread();
- tt.run();
- }
- }
-
- class TestThread extends Thread {
- static int i = 0;
- final static int MAX_I = 10;
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while (i < MAX_I) {
- System.out.println(i++);
- }
- }
- }
運行結果如下:
[java] view plain copy
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
或許有人會得出結論,這樣啟動一個線程是可以的,我們再對程式稍做修改,大家就會發現一個問題:
[java] view plain copy
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TestThread tt = new TestThread();
- tt.run();
- System.out.println("Printed by main thread");
- }
- }
-
- class TestThread extends Thread {
- static int i = 0;
- final static int MAX_I = 10;
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while (i < MAX_I) {
- System.out.println(i++);
- }
- }
-
- }
這裡只在主線程中加入了一行代碼,打印一行"Printed by main thread",運行代碼,結果如下:
[xhtml] view plain copy
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- Printed by main thread
熟練多線程開發的要發現問題了,為什麼"Printed by main thread"會打印在最後一行呢?TestThread類中一直持有時間段嗎?
我們對上面的代碼進行分析,其實非常簡單,這只是一個普通的類中方法的調用,其實是一個單線程的執行,我們來修改代碼進一步驗證這一點:
[java] view plain copy
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TestThread tt = new TestThread();
- tt.run();
- System.out.println(Thread.currentThread().getName());
- System.out.println("Printed by main thread");
- }
- }
-
- class TestThread extends Thread {
- static int i = 0;
- final static int MAX_I = 10;
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println(Thread.currentThread().getName());
- while (i < MAX_I) {
- System.out.println(i++);
- }
- }
- }
這段代碼分別在主線程和我們的TestThread的方法中打印當前線程名字,運行結果如下:
[xhtml] view plain copy
- main
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- main
- Printed by main thread
在TestThread類和主線程中運行的是同一個線程,說明在直接調用run時是不能使用多線程的,那麼把上面的run方法調用改為start方法的調動再看一下:
[java] view plain copy
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TestThread tt = new TestThread();
- tt.start();
- System.out.println(Thread.currentThread().getName());
- System.out.println("Printed by main thread");
- }
- }
-
- class TestThread extends Thread {
- static int i = 0;
- final static int MAX_I = 10;
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println(Thread.currentThread().getName());
- while (i < MAX_I) {
- System.out.println(i++);
- }
- }
- }
運行結果如下:
[xhtml] view plain copy
- main
- Thread-0
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- Printed by main thread
- 9
很明顯,這才是我們想看到的結果,所以結論是只有調用Thread的start方法,將線程交由JVM控制,才能產生多線程,而直接調用run方法只是一個普通的單線程程式。