Java 17 Recipes


-6. Splitting Work into Separate Threads


Download 3.2 Mb.
Pdf ko'rish
bet191/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   187   188   189   190   191   192   193   194   ...   245
Bog'liq
Java 17 Recipes

10-6. Splitting Work into Separate Threads
 Problem
You have work that can be split into separate threads and want to maximize available 
CPU resources.
 Solution
Use a ThreadpoolExecutor instance, which allows you to break the tasks into discrete 
units. In the following example, a BlockingQueue interface is created, including a 
Runnable object. It then is passed to the ThreadPoolExecutor instance, which is then 
initialized and started by calling the prestartAllCoreThreads() method. Next, perform 
an orderly shutdown in which all previously submitted tasks are executed by calling the 
shutdown() method, followed by the awaitTermination() method.
private void start() throws InterruptedException {
BlockingQueue queue = new LinkedBlockingQueue<>();
for (int i =0;i < 10;i++) {
final int localI = i;
queue.add((Runnable) () -> {
Chapter 10 ConCurrenCy


373
doExpensiveOperation(localI);
});
}
ThreadPoolExecutor executor = new ThreadPoolExecutor(10,10,1000,
TimeUnit.MILLISECONDS, queue);
executor.prestartAllCoreThreads();
executor.shutdown();
executor.awaitTermination(100000,TimeUnit.SECONDS);
System.out.println("Look ma! all operations were completed");
}
public static void main (String [] args) throws InterruptedException {
Recipe10_6 recipe = new Recipe10_6();
recipe.start();
}
private void doExpensiveOperation(int index) {
System.out.println("Starting expensive operation "+index);
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Ending expensive operation " + index);
}
The following is the output.
Starting expensive operation 1
Starting expensive operation 3
Starting expensive operation 2
Starting expensive operation 0
Starting expensive operation 4
Ending expensive operation 0
Starting expensive operation 6
Starting expensive operation 5
Starting expensive operation 7
Starting expensive operation 8
Chapter 10 ConCurrenCy


374
Starting expensive operation 9
Ending expensive operation 1
Ending expensive operation 2
Ending expensive operation 3
Ending expensive operation 4
Ending expensive operation 5
Ending expensive operation 6
Ending expensive operation 7
Ending expensive operation 8
Ending expensive operation 9
Look ma! all operations were completed

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   187   188   189   190   191   192   193   194   ...   245




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