Exact problem statement:
A main thread spawns 2 new threads, the main thread waits on this threads with these conditions:
- if any of the threads returns True, then main thread moves on and prints the thread_id and timestamp of the thread.
- if both threads return false, finish execution and don't print anything
My attempt:
public static void main(String[] args) throws InterruptedException, ExecutionException{
FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
System.out.println("Hello, World 1!");
return true;
});
FutureTask<Boolean> futureTask2 = new FutureTask<>(() -> {
System.out.println("Hello, World 2!");
return true;
});
Thread t1 = new Thread(futureTask);
Thread t2 = new Thread(futureTask2);
t1.start();
t2.start();
// Wait for either to be done.
while (!futureTask.isDone() && !futureTask2.isDone());
if (futureTask.isDone()) {
if (futureTask.get()) {
System.out.println("1 - " + t1.getId() + " " + System.currentTimeMillis());
return;
}
}
if (futureTask2.isDone()) {
if (futureTask2.get()) {
System.out.println("2 - " + t2.getId() + " " + System.currentTimeMillis());
return;
}
}
}
}
When I run this a few times, sometimes thread 1 wins, sometimes 2, which seems to make sense to me. Appreciate any room for improvement or advice.