In this chapter you have learned about threads and how you can create and manage them. We will be using threads from time to time in examples later in this book so be sure you don't move on from here without being comfortable with the basic ideas of how you create and start a thread.
The essential points that we have covered in this chapter are:
Threads are subtasks in a program that can be in execution concurrently.
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.
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.
A thread specified as daemon will cease execution when the thread that created it ends.
A thread that isn't a daemon thread is called a user thread. A user thread will not be terminated automatically when the thread that created it ends.
You 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.
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.
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.
In a synchronized method or code block, you can call the wait() method inherited from the class Object to halt execution of a thread. Execution of the waiting thread will continue when the notify() or notifyAll() method inherited from Object is called by a thread synchronized on the same object.
The notify() or notifyAll() method can only be called from a method or code block that is synchronized to the same object as the method or block that contains the wait() method that halted the thread.
You can modify the relative priority of a thread by calling its setPriority() method. This only has an effect on execution in environments that support priority scheduling.