我创建了三个线程,如client1,client2,client3,相应的读取请求“读取2”,“读取1”,“读取3”。我想以下列方式处理读取请求:
Client2读取1
Client1阅读2
Client3阅读3
我不知道先运行一个线程(client2)然后根据读取请求顺序运行线程(client1)等。有一个条件我不能在我的程序中使用sleep。
如果有人知道解决方案,请在上述问题的背景下提供帮助。
答案 0 :(得分:0)
根据程序的复杂程度,可以使用2 CountDownLatch
来同步您的主题,一个Client1
一旦Client2
完成阅读,另一个释放Client3
{1}} 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
无论线程的起始顺序如何,这种方法都可以保证获得正确的读取序列。