Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet182/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   178   179   180   181   182   183   184   185   ...   245
Bog'liq
Java 17 Recipes

 How It Works
The Thread class allows executing code in a new thread (path of execution), distinct 
from the current thread. The Thread constructor requires as a parameter a class that 
implements the Runnable interface. The Runnable interface requires implementing only 
one method: public void run(). Hence, it is a functional interface, which facilitates 
the use of lambda expressions. When the Thread.start() method is invoked, it creates a 
new thread and invokes the run() method from the Runnable interface.
Within the JVM are two types of threads: User and Daemon. User threads keep 
executing until their run() method completes, whereas Daemon threads can be 
terminated if the application needs to exit. An application exits if there are only Daemon 
threads running in the JVM. When you start to create multithreaded applications, you 
must be aware of these differences and understand when to use each type of thread.
Usually, Daemon threads have a Runnable interface that doesn’t complete; for 
example, a while (true) loop. This allows these threads to periodically check or 
perform a certain condition throughout the life of the program and be discarded when 
the program is finished executing. If you happen to have a program that is not closing 
and/or exiting when expected, you might want to check the threads that are actively 
running. To set a thread as a Daemon thread, use thread.setDaemon(true) before 
calling the thread.start() method.
Chapter 10 ConCurrenCy


354
10-2. Updating (and Iterating) a Map
 Problem
You need to update a Map object from multiple threads, and you want to make 
sure that the update doesn’t break the contents of the Map object and that the Map object 
is always in a consistent state. You also want to traverse (look at) the content of the Map 
object while other threads are updating the Map object.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   178   179   180   181   182   183   184   185   ...   245




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