2013年7月29日 星期一

[JAVA] Thread中run()跟start()的差別

一個簡單的Thread宣告
Thread t1 = new Thread(new Runnable() {
 @Override
 public void run() {
  for (int i = 0; i <= 3; i++) {
   System.out.println("T1: " + i + ", Thread name: "
     + Thread.currentThread().getName());
  }
 }
});

Thread t2 = new Thread(new Runnable() {
 @Override
 public void run() {
  for (int j = 0; j <= 3; j++) {
   System.out.println("T2: " + j + ", Thread name: "
       + Thread.currentThread().getName());
  }
 }
});


要執行這個Thread有幾種方法
本文來比較run()跟start()的差異

//=============================================

1. run()
是由執行中的執行緒負責呼叫,也就是main
用這種方式呼叫,並沒有達到Thread的意義

假設使用run呼叫Thread
t1.run();
t2.run();
出來的結果
T1: 0, Thread name: main
T1: 1, Thread name: main
T1: 2, Thread name: main
T1: 3, Thread name: main
T2: 0, Thread name: main
T2: 1, Thread name: main
T2: 2, Thread name: main
T2: 3, Thread name: main


2. start()
由new Thread所建立的Thread負責執行

假設使用start()呼叫Thread
t1.start();
t2.start();
出來的結果,每條Thread會依據CPU分配的時間而有不同的執行順序
T1: 0, Thread name: Thread-0
T1: 1, Thread name: Thread-0
T2: 0, Thread name: Thread-1
T1: 2, Thread name: Thread-0
T2: 1, Thread name: Thread-1
T2: 2, Thread name: Thread-1
T1: 3, Thread name: Thread-0
T2: 3, Thread name: Thread-1

沒有留言:

張貼留言