面試官 如何控制多執行緒執行順序?

2021-09-02 21:55:58 字數 1811 閱讀 6210

先看如下**:

public

class

test);

static thread thread2 =

newthread((

)->);

static thread thread3 =

newthread((

)->);

public

static

void

main

(string[

] args)

throws interruptedexception

}

重複執行多次,發現輸出並不是按照執行緒的啟動順序來執行。因為這個裡面涉及到cpu對執行緒的排程問題。

thread1

thread3

thread2

如何讓thread1,thread2,thread3順序執行呢?

通過join方法去保證多執行緒順序執行

public

class

test);

static thread thread2 =

newthread((

)->);

static thread thread3 =

newthread((

)->);

public

static

void

main

(string[

] args)

throws interruptedexception

}

可以看到輸出一直是如下

thread1

thread2

thread3

join是怎麼實現這個功能的呢?

join方法讓主線程等待子執行緒結束以後才能繼續執行,因此保證了執行緒的順序執行

使用單例執行緒池,用唯一的工作執行緒執行任務,保證所有任務按照指定順序執行

executorservice executorservice = executors.

newsinglethreadexecutor()

;

這個會把執行緒放在乙個fifo佇列,依次執行執行緒

public

class

test);

static thread thread2 =

newthread((

)->);

static thread thread3 =

newthread((

)->);

static executorservice executorservice = executors.

newsinglethreadexecutor()

;public

static

void

main

(string[

] args)

throws interruptedexception

}

輸出一直為

thread1

thread2

thread3

目的達到

如何控制多執行緒執行順序

如果我們new了好幾個執行緒,然後開始執行,肯定不是按照順序執行的,因為多執行緒.start 方法開始執行之後,並不意味著立即執行,而是到就緒狀態,等待cpu的排程,cpu如何排程,那我們就沒法知道了,但是如何讓執行緒按照指定的順序來執行呢?我們可以利用執行緒的join方法。join 方法的主要作用...

如何控制多執行緒執行順序

如果我們new了好幾個執行緒,然後開始執行,肯定不是按照順序執行的,因為多執行緒.start 方法開始執行之後,並不意味著立即執行,而是到就緒狀態,等待cpu的排程,cpu如何排程,那我們就沒法知道了,但是如何讓執行緒按照指定的順序來執行呢?我們可以利用執行緒的join方法。join 方法的主要作用...

控制多執行緒執行順序

雖然專案用不上,先備份吧,控制多執行緒執行順序有兩種方法 1.通過join方法保證多執行緒的順序性的特性 join 讓主線程等待子執行緒結束後才能繼續執行 public static void main string args throws interrupterexception 2.excuto...