具體解釋請看註釋
package concurrent;
/*
* @author: wjf
* @version: 2016年3月27日 下午1:54:41
*/
public class TestRunnable {
public static void main(String[] args){
MyRunnable run=new MyRunnable();
Thread th=new Thread(run);
th.start();
System.out.println(Thread.currentThread().getId());
/*
* 可以發現下面的運行結果和 主線程的 id 一樣,run 方法只是爲了定義將要運行的任務,線程的啓動還是需要start()
* 直接調用run ,不會啓動一個新的線程的。
*
* 另外說明一點 使用runnable 和直接 使用thread 的區別
* runnable 是一個藉口,thread 是一個 已經實現了該藉口的類
* 使用thread 代碼看起來要簡潔一點,另外由於 java 中只有單繼承,當需要繼承時,可能只能實現runnable 藉口
*/
run.run();
}
}
class MyRunnable implements Runnable{
public MyRunnable(){
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getId());
}
}