1谨湘、Java中如何讓多線程按照自己指定的順序執(zhí)行?
方法1:
通過(guò)thread.join的方法來(lái)實(shí)現(xiàn)
thread.join的含義為蝙昙,當(dāng)主線程創(chuàng)建子線程轻局,調(diào)用子線程的start的方法,這時(shí)子線程是運(yùn)行狀態(tài)挡毅,然后主線程調(diào)用子線程的join方法蒜撮,主線程陷入阻塞,
等到子線程執(zhí)行完畢跪呈,然后在喚醒主線程段磨,繼續(xù)執(zhí)行下邊的子線程。
package com.inspur.thread;
public class ThreadOrder {
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1執(zhí)行");
}
});
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2執(zhí)行");
}
});
static Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread3執(zhí)行");
}
});
public static void main(String[] args) throws InterruptedException {
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
}
}
從join方法的源碼來(lái)看耗绿,join方法的本質(zhì)調(diào)用的是Object中的wait方法實(shí)現(xiàn)線程的阻塞苹支。調(diào)用wait方法必須要獲取鎖,所以join方法是被synchronized修飾的误阻,
synchronized修飾在方法層面相當(dāng)于synchronized(this)债蜜,(后續(xù)補(bǔ)充這一塊)
主線程會(huì)持有對(duì)象的鎖,然后調(diào)用wait方法去阻塞究反,而這個(gè)方法的調(diào)用者是在主線程中的寻定。所以造成主線程阻塞。
方法2:
使用ExecutorService ,利用newSingleThreadExecutor奴紧,這個(gè)線程池特姐,其實(shí)是隊(duì)列晶丘,使線程進(jìn)入隊(duì)列進(jìn)行排隊(duì)執(zhí)行
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);