Seventh Chapter Multithreading
I. Thread class and Runnable interface
1. The runnable interface and the thread class are defined in the Java.lang package.
Only one method is defined in the Runnable interface, which is in the following format:
public abstract void Run ()
2. This method is implemented by a class that implements the Runnable interface. A Runnable object is called a running object, and a thread runs the run () method that executes the object.
The 3.Thread class implements the Runnable interface, so the thread object is also a running object. The thread class is also a threading class.
4.target is the target object that the thread runs on, that is, the thread calls the start () method to run the object after it is started (), the type of the object is runnable, and if no target object is specified, the current class object is the target object; name is the thread name. group specifies which thread group the thread belongs to.
Two. Creation of threads
The code that runs the thread is the run () method of the class that implements the Runnable interface, or the run () method of the subclass of the thread class, so there are two ways to construct the thread body:
Inherit the thread class and overwrite its run () method;
Implement the Runnable interface and implement its run () method.
Inheriting the thread class to create threads
By inheriting the thread class and overriding the run () method, you can use an instance of the class as the target object for the thread. The following program defines the Simplethread class, which inherits the thread class and overrides the run () method.
Implementing the Runnable Interface creation thread
You can define a class to implement the Runnable interface, and then use that class object as the target object for the thread. Implementing the Runnable interface is the implementation of the run () method.
Three. Thread Life cycle
Threads are always in one of the following five states from creation, run to end: New state, ready state, running state, blocking state, and death status.
NEW: Create a thread
Ready: Waiting to start
Run: Run output
Blocking: Returning blocking state from run
Death: End of program
Using Java to implement object-oriented seventh chapter