[英]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.