Java Reference
In-Depth Information
Thread backgroundThread = new
Thread(this::doSomethingInBackground, "Background
Thread");
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 the imple-
mentation of only one method:
public void run()
. Hence, it is a functional in-
terface, which facilitates the use of lambda expressions. When the
Thread.start()
method is invoked, it will in turn create the new thread and invoke the
run()
method
of the
Runnable
.
Within the JVM are two types of threads: User and Daemon. User threads keep ex-
ecuting until their
run()
method completes, whereas Daemon threads can be termin-
ated 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 will 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. In contrast,
User
threads, while alive, will ex-
ecute and prevent the program from terminating. 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. By default,
Thread
instances are created as
User
thread types.
Note
This recipe shows the simplest way to create and execute a new thread. The
new thread created is a
User
thread, which means that the application will not exit until
both the main thread and the background thread are done executing.
10-2. Updating (and Iterating) a Map