my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing task1 ) and a Thread t2 (for task2 ). I want then to do a specific task, task3 when both other tasks (1 & 2) are over. Naturally I can't tell which of task1 and task2 will finish first...
Which would be for you the simplest (and safest) way to code this ?
Thank you for your help
You've got several options:
您可以join
t1
和t2
(按任意顺序),然后在加入后运行task3。
Implement a listener interface in your task3, and register it to both task1 & task2. Task1 and Task2 will have to call their listener just before ending. Doing so, you can record in task3 which task has already finished, and when both have finished, you can perform your third task.
Of course, if on of your task1/2 can exit with an exception, don't forget to put task3 as its UncaughtExceptionHandler
I you don't want to terminate the 2 worker threads (task1 and task2) when they finish their job, then you can wait on a condition in task3 until the other two finish. Something like this:
public class Master {
private Object monitor_ = new Object();
private boolean task1Finished_;
private boolean task2Finished_;
class Task1 extends Thread {
public void run() {
// do stuff
synchronized (monitor_) {
task1Finished_ = true;
monitor_.notifyAll();
}
// keep on working
}
}
class Task2 extends Thread {
public void run() {
// do stuff
synchronized (monitor_) {
task1Finished_ = true;
monitor_.notifyAll();
}
// keep on working
}
}
class Task3 extends Thread {
public void run() {
synchronized (monitor_) {
while (!task1Finished_ || !task2Finished_) {
try {
monitor_.wait();
}
catch (InterruptedException ignored) {
}
}
}
// do stuff
}
}
// start tasks1, task2 and task3...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.