Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet194/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   190   191   192   193   194   195   196   197   ...   245
Bog'liq
Java 17 Recipes

 Solution 2
You can control when the main thread continues using a CountDownLatch object. In 
the following code, a CountDownLatch with an initial value of 2 is created; then, the two 
threads for loading the inventory and loading the order information are created and 
Chapter 10 ConCurrenCy


378
started. As each of the two threads finishes executing, they call the CountDownLatch’s 
countDown() method, which decrements the latch’s value by one. The main thread waits 
until the CountDownLatch reaches 0, at which point it resumes execution.
public static void main(String[] args) {
Recipe10_7_2 recipe = new Recipe10_7_2();
recipe.start();
}
CountDownLatch latch = new CountDownLatch(2);
private void start() {
loadItems();
Thread inventoryThread = new Thread(() -> {
System.out.println("Loading Inventory from Database...");
loadInventory();
latch.countDown();
});
inventoryThread.start();
Thread ordersThread = new Thread(() -> {
System.out.println("Loading Orders from XML Web service...");
loadOrders();
latch.countDown();
});
ordersThread.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
processOrders();
}
The following is the output.
Loading Inventory from Database...
Loading Orders from XML Web service...
Order # 0 has been fulfilled
Order # 1 has been fulfilled
Chapter 10 ConCurrenCy


379
Order # 2 has been fulfilled
Order # 3 has been fulfilled
Order # 4 has been fulfilled
Order # 5 has been fulfilled
Order # 6 has been fulfilled
Order # 7 has been fulfilled
Order # 8 has been fulfilled
Order # 9 has been fulfilled
Order # 10 has been fulfilled
Order # 11 has been fulfilled
Order # 12 has been fulfilled
Order # 13 has been fulfilled
...

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   190   191   192   193   194   195   196   197   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling