學習 多執行緒順序列印ABC

2021-10-24 06:12:27 字數 2156 閱讀 2712

深夜睡不著,更新一波,突然想起了兩個月之前的一次面試的懊悔。為什麼懊悔呢,因為面試官出的題很簡單很簡單,但是我想太多了,導致出糗了。

題目,有三個執行緒,按順序列印123。

public

class

test1

extends

thread})

; thread b=

newthread

(new

runnable()

}); thread c=

newthread

(new

runnable()

});//按順序列印123

}}

可能是看了太多面試題,拿到題目第一時間想到了用synchronized,lock來鎖住,然後乙個乙個釋放,然後因為緊張,方法都寫錯了花了很長時間。後面面試官笑了笑說:「我也沒說一定要啟動執行緒呀!」。我瞬間恍然大悟,也為自己想太多而感到困窘。

面試官說的不啟動執行緒方法

方法一,直接使用run()方法,按順序列印。

a.

run();

b.run()

;c.run(

);

面試結束後,整理出來三個方法

方法二,使用sleep()暫停執行緒,確保按順序列印

a.

start()

;thread.

sleep

(100);

b.start()

;thread.

sleep

(100);

c.start()

;

方法三,使用thread類的封裝方法setpriority(),設定優先順序

(ps:正常時候按優先順序開啟執行緒,但是網上有人說有時候會因為cpu排程而不按優先順序,但是我測試還沒見過,有待考察)

a.

setpriority(3

);a.start()

;b.setpriority(2

);b.start()

;c.setpriority(1

);c.start()

;

方法四,使用join(),是開啟下乙個執行緒是進行驗證

package com.jhuo;

public

class

test2})

;// 執行緒b

final thread b =

newthread

(new

runnable()

catch

(interruptedexception e)

system.out.

println

("b");

}});

// 執行緒c

final thread c =

newthread

(new

runnable()

catch

(interruptedexception e)

system.out.

println

("c");

}});

// 執行緒d

thread d =

newthread

(new

runnable()

catch

(interruptedexception e)

system.out.

println

("d");

}});

//方法四

a.start()

; b.

start()

; c.

start()

; d.

start()

;}}

這道題其實不需要用到synchronized和lock,加鎖通常是用在多個執行緒併發使用同乙個資源導致執行緒不安全,雖然理論上也可以加鎖,釋放,開啟下乙個執行緒,但是這樣意義不大,而且效率會降低。這個面試題是我的第一次面試,雖然沒有過,不知道是不是這道題的原因,但是確實提醒了我不能只注重開發,還要鞏固基礎和原理,才能在程式設計師這條道路上越走越遠。

多執行緒之abc順序列印10次

package com.ghgj.cn.thread public class threadabc catch interruptedexception e system.out.println a thread1 false 保證本執行緒不死 thread2 true 喚醒2執行緒 thread3...

多執行緒順序列印ABC 實現讀寫鎖

1 多執行緒順序列印abc include include include include sem t sem id1,sem id2,sem id3 void func1 void 宣告 void func2 void void func3 void int main void void func...

多執行緒按順序列印

於leetcode1114 我們提供了乙個類 public class foo public void second public void third 三個不同的執行緒將會共用乙個 foo 例項。請設計修改程式,以確保 second 方法在 first 方法之後被執行,third 方法在 seco...