多線程的創(chuàng)建方式
- 定義 Thread 類的子類創(chuàng)建
/**
* @author: kent
* @date: 2018/4/18 09:40
*/
public class WelcomeApp {
public static void main(String[] args) {
//create new thread
Thread welcomeThread = new WelcomeThread();
welcomeThread.start();
System.out.printf("1. Welcome ! I'm %s.%n",Thread.currentThread().getName());
}
}
class WelcomeThread extends Thread{
@Override
public void run(){
System.out.printf("2. Welcome ! I'm %s.%n",Thread.currentThread().getName());
}
}

image.png
多次執(zhí)行程序得到的結(jié)果可能不同
- 創(chuàng)建 Runnable 接口實例
/**
* @author: kent
* @date: 2018/4/18 09:48
*/
public class WelcomeApp1 {
public static void main(String[] args) {
//創(chuàng)建線程
Thread welcomeThread = new Thread(new WelcomeTask());
welcomeThread.start();
System.out.printf("1. welcome ! I'm %s.%n",Thread.currentThread().getName());
}
}
class WelcomeTask implements Runnable{
@Override
public void run(){
System.out.printf("2. Welcome ! I'm %s.%n",Thread.currentThread().getName());
}
}

image.png
多次執(zhí)行程序得到的結(jié)果可能不同
避免應(yīng)用代碼直接調(diào)用線程的 run 方法
/**
* @author: kent
* @date: 2018/4/18 10:32
*/
public class WelcomeApp2 {
public static void main(String[] args) {
Thread welcomeThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.printf("2. welcome ! I'm %s.%n",Thread.currentThread().getName());
}
});
welcomeThread.start();//啟動線程
welcomeThread.run();//直接調(diào)用,其實運行在main線程里面
System.out.printf("1. welcome ! I'm %s.%n",Thread.currentThread().getName());
}
}

image.png
多次執(zhí)行程序得到的結(jié)果可能不同
比較兩種創(chuàng)建方式
從面向?qū)ο蟮慕嵌葋碚f:第一種創(chuàng)建方式(創(chuàng)建Thread的子類)是一種基于繼承(Inheritance)的技術(shù),第二種創(chuàng)建方式(以Runnable接口實例為構(gòu)造器參數(shù)直接通過 new 創(chuàng)建 Thread 實例)是一種基于組合的(Composition)技術(shù),由于組合相對于繼承來說耦合性(Coupling)更低,因此更加靈活。組合是優(yōu)先選用的技術(shù)