我有兩個同步的代碼塊。我需要兩個代碼塊不能同時在兩個或更多不同的線程中運行,但我會想要允許兩個或更多個不同的線程同時運行代碼塊的一個一個。這怎麼能在Java中完成?爲了舉例說明:微調Java同步塊行爲
class HelloWorld {
method1() {
synchronized (?) { //block 'A'
//I want to allow 2+ threads to run this code block simultaneously
}
}
method2() {
synchronized (?) { //block 'B'
//this should block while another thread is running
//the synchronized block 'A'
}
}
我不想都同步塊鎖定在同一個對象/類,因爲那樣會被多個線程同時運行不允許的第一個塊。但是,這是我知道阻止塊A和B同時運行2個或更多線程的唯一途徑。必須有一種方法來實現這一點。
我會重新考慮你爲什麼需要這個,因爲最有可能實現您的解決方案的方式,所以這是不是必需的。 –
爲什麼名爲HelloWorld的類?這是你第一次嘗試Java嗎?如果是這樣,遠離併發。 – Kayaman
卡亞曼,班級名稱有什麼不同?這是您第一次嘗試提供有用的評論嗎? – bitsmcgee77