Parallel task - solution with CountDownLatch
konradin23
java
02/19/2026 10:45 AM
2.1 KB
11
Indexable
import java.util.concurrent.CountDownLatch;
public class DashboardLoader {
public void loadDashboard() throws InterruptedException {
long start = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(3);
new Thread(() -> {
try {
loadUserData();
} catch (InterruptedException ignored) {
} finally {
latch.countDown();
}
}).start();
new Thread(() -> {
try {
loadOrderHistory();
} catch (InterruptedException ignored) {
} finally {
latch.countDown();
}
}).start();
new Thread(() -> {
try {
loadRecommendations();
} catch (InterruptedException ignored) {
} finally {
latch.countDown();
}
}).start();
latch.await();
System.out.println("All data loaded");
System.out.println("Total time: " +
(System.currentTimeMillis() - start) + " ms");
}
private void loadUserData() throws InterruptedException {
Thread.sleep(2000);
System.out.println("User data loaded");
}
private void loadOrderHistory() throws InterruptedException {
Thread.sleep(3000);
System.out.println("Order history loaded");
}
private void loadRecommendations() throws InterruptedException {
Thread.sleep(2500);
System.out.println("Recommendations loaded");
}
}
Editor is loading...
Leave a Comment