[英]facing Java multithread concurrency issue
我創建了三個線程,如client1,client2,client3,相應的讀取請求“讀取2”,“讀取1”,“讀取3”。 我想以下列方式處理讀取請求:
Client2閱讀1
Client1閱讀2
Client3閱讀3
我不知道先運行一個線程(client2)然后根據讀取請求序列線程(client1)等等。有一個條件,我不能在我的程序中使用sleep。
如果有人知道解決方案,請在上述問題的上下文中提供幫助。
根據你的程序的復雜性,它可以使用2做CountDownLatch
同步你的線程,一個釋放Client1
,一旦Client2
已經讀完,另一種釋放Client3
一旦Client1
已經讀完。
// Used to release client1
CountDownLatch startThread1 = new CountDownLatch(1);
Thread client2 = new Thread(
() -> {
System.out.println("Read 1");
// Release client1
startThread1.countDown();
}
);
// Used to release client3
CountDownLatch startThread3 = new CountDownLatch(1);
Thread client1 = new Thread(
() -> {
try {
// Waiting to be released
startThread1.await();
System.out.println("Read 2");
// Release client3
startThread3.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
);
Thread client3 = new Thread(
() -> {
try {
// Waiting to be released
startThread3.await();
System.out.println("Read 3");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
);
// Start the threads in reverse order intentionally to show that
// we still have the expected order
client3.start();
client1.start();
client2.start();
輸出:
Read 1
Read 2
Read 3
無論線程的起始順序如何,這種方法都可以保證獲得正確的讀取順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.