Java 17 Recipes


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

 How It Works
ThreadPoolExecutor consists of two components: Queue, the tasks to be executed, 
and Executor, which tells how to execute the tasks. Queue is filled with Runnable 
objects, on which the run() method contains the code to be executed.
The Queue component used by ThreadPoolExecutor is an implementer of the 
BlockingQueue interface, which denotes a queue in which the consumers of the 
queue wait (be suspended) if there are no elements within Queue. This is necessary 
for ThreadPoolExecutor to work efficiently.
The first step is to fill Queue with the tasks that need to be executed in parallel. 
This is done by calling Queue’s add() method and passing a class that implements the 
Runnable interface. Once that’s done, the executor is initialized.
After ThreadPoolExecutor is initialized, you call the prestartAllCoreThreads() 
method, which “warms up” ThreadPoolExecutor by creating the number of threads 
specified in CorePoolSize and actively starts consuming tasks from Queue if it is 
not empty.
Call the shutdown() method from ThreadPoolExecutor to wait for all the tasks to 
complete. By calling this method, ThreadPoolExecutor is instructed to accept no new 
events from the queue (previously submitted events finish processing). This is the first 
step in the orderly termination of ThreadPoolExecutor. Call the awaitTermination() 
method to wait for all the tasks in ThreadPoolExecutor to be done. This method forces 
the main thread to wait until all Runnable objects in ThreadPoolExecutor’s queue have 
completed executing. After all Runnable objects have been executed, the main thread 
wakes up and continues.
Chapter 10 ConCurrenCy


375
10-7. Coordinating Threads
 Problem
Your application requires that two or more threads be coordinated to work in unison.

Download 3.2 Mb.

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




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