按順序執行執行緒

2021-10-11 03:05:15 字數 2414 閱讀 1837

condition介面提供了類似object的監視器方法,與lock配合可以實現等待/通知模式。

condition定義了等待/通知兩種型別的方法,當前執行緒呼叫這些方法時,需要提前獲取到condition物件關聯的鎖。condition物件是由lock物件(呼叫lock物件的newcondition()方法)建立出來的,換句話說,condition是依賴lock物件的。

/**

* **中的

* condition.await() 可以用 this.wait() 替代

* condition.signalall() 可以用 this.notifyall() 替代

*/class

data

num++

; system.out.

println

(thread.

currentthread()

.getname()

+"=>"

+ num)

;

condition.

signalall()

;}catch

(interruptedexception e)

finally

}public

void

decrement()

num--

; system.out.

println

(thread.

currentthread()

.getname()

+"=>"

+ num)

;

condition.

signalall()

;}catch

(interruptedexception e)

finally

}}

/**

* condition 精準的通知和喚醒執行緒!

* * 案例:按順序列印出 a、b、c

* * 宣告 num

* num = 1 時,列印 a

* num = 2 時,列印 b

* num = 3 時,列印 c

* * 在 showa 中使num = 2 ,滿足 showb 條件

* 在 showa 中使num = 3 ,滿足 showc 條件

* 在 showa 中使num = 1 ,滿足 showa 條件

* 以此來使其按照順序列印

* * @author dsstart

* @create 2020-12-02 15:12

*/public

class

jucversion2},

"執行緒a:").

start()

;new

thread((

)->},

"執行緒b:").

start()

;new

thread((

)->},

"執行緒c:").

start()

;}}class

data

num =2;

system.out.

println

(thread.

currentthread()

.getname()

+"*****a*****");

conditionb.

signal()

;}catch

(interruptedexception e)

finally

}public

void

showb()

num =3;

system.out.

println

(thread.

currentthread()

.getname()

+"*****b*****");

conditionc.

signalall()

;}catch

(interruptedexception e)

finally

}public

void

showc()

num =1;

system.out.

println

(thread.

currentthread()

.getname()

+"*****c*****");

conditiona.

signal()

;}catch

(interruptedexception e)

finally

}}

讓執行緒乖乖 按順序執行

1 join 等你執行結束,我再執行 2 singlethreadpool 只有乙個執行緒的執行緒池,任務乖乖在佇列中等待被執行 3 wait notify機制 兄弟們,醒醒,到你了 4 reentrantlock 的 condition 的 await signal機制 那個兄弟,醒醒,到你了 接...

如何保證執行緒按順序執行

有三個執行緒t1 t2 t3,如何保證他們按順序執行 在t2的run中,呼叫t1.join,讓t1執行完成後再讓t2執行 在t2的run中,呼叫t2.join,讓t2執行完成後再讓t3執行 public class threadbyorder static thread t2 new thread ...

如何讓執行緒按順序執行

join waits for this thread to die.等待此執行緒結束 join long millis waits at most milliseconds for this thread to die.a timeout of 0 means to wait forever.設定加...