Java Reference
In-Depth Information
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
Threads
Threads are subtasks in a program that can be executing concurrently.
Thread Ob-
jects
A thread is represented by an object of the class Thread . Execution of a thread begins with the execution
of the run() method defined in the class Thread.
Thread Code You define the code to be executed in a thread by implementing the run() method in a class derived
from Thread , or in a class that implements the interface Runnable.
Daemon
Threads
A thread specified as daemon ceases execution when the thread that created it ends.
User Threads A thread that isn't a daemon thread is called a user thread. A user thread is not terminated automatically
when the thread that created it ends.
Starting a
Thread
You can start execution of a thread by calling the start() method for its Thread object. If you need to
halt a thread before normal completion, you can stop execution of a thread by calling the interrupt()
method for its Thread object.
Synchronized
Methods
Methods can be declared as synchronized . Only one synchronized instance method for an object can
execute at any given time. Only one synchronized static method for a class can execute at one time.
Synchronized
Code Blocks
A code block can be declared as synchronized on an object. Only one synchronized code block for an
object can execute at any given time.
Deadlocks
A deadlock is a situation in which two threads are both waiting for the other to complete some action.
Deadlocks can occur in subtle ways in multi-threaded applications, which makes such applications diffi-
cult to debug.
Executors
An executor is an object that can create, manage, and start threads.
Creating an
Executor
You create an executor object by calling one of the static methods defined in the Executors class.
Thread Pools You can create executors that provide a thread pool with a fixed number of threads that may be reused or
with an unlimited number of threads.
Threads
Returning a
Value
A thread that returns a value is defined by a class that implements the Callable<V> interface. This inter-
face defines the call() method that returns a value of type V .
A Future<V> object is returned by the submit() method for an ExecutorService object that starts a
thread. You can use the object returned to manage the thread and to obtain the result of a Callable<>
thread.
Future<V>
Objects
Thread Prior-
ities
You can modify the relative priority of a thread by calling its setPriority() method. This has an effect
on execution only in environments that support priority scheduling.
Search WWH ::




Custom Search