Java Reference
In-Depth Information
of tasks that are submitted. If the tasks are CPU-intensive, having an executor with the
current number of cores would be ideal. If the tasks are I/O-intensive, the executor
should have more threads than the current number of cores of threads. The more I/O-
bound, the higher the number of threads.
10-7. Coordinating Threads
Problem
Your application requires that two or more threads be coordinated to work in unison.
Solution 1
With wait/notify for thread synchronization, threads can be coordinated. In this solu-
tion, the main thread waits for the objectToSync object until the database-loading
thread is finished executing. Once the database-loading thread is finished, it notifies the
objectToSync that whomever is waiting on it can continue executing. The same
process occurs when loading the orders into our system. The main thread waits on ob-
jectToSync until the orders-loading thread notifies objectToSync to continue by
calling the objectToSync.notify() method. After ensuring that both the invent-
ory and the orders are loaded, the main thread executes the processOrder() meth-
od to process all orders.
private final Object objectToSync = new Object();
private void start() {
loadItems();
Thread inventoryThread = new Thread(() -> {
System.out.println("Loading Inventory from
Database...");
loadInventory();
synchronized (objectToSync) {
objectToSync.notify();
}
Search WWH ::




Custom Search