In Java, there are two methods to implement multi-threaded code. One is to inherit the Thread class, and the other is to implement the runnable interface.
AIn the thread subclass, you must explicitly override the run () method in the Thread class. This method is the main body of the thread. In the process of calling the START () method, what is actually called is
Private native void start0 (). The native keyword declaration is used here. This keyword indicates that the local operating system function is called, because the implementation of multithreading depends on
Supports the underlying operating system.
B can also implement multithreading by implementing the runnable interface in Java. the runnable interface only defines one abstract method:
Public void run ();
To implement the START () method in ruunable, you still need to rely on the Thread class to start.
Public thread (runnable target) and Public thread (runnable target, string name) constructor.
Both constructor methods can receive runnable sub-class instance objects, so you can start multithreading with this point.
The run () method in the Thread class calls the run () method in the runnable interface, that is, this method is completed by the runnable subclass, so
To implement multithreading by inheriting the Thread class, you must override the run () method.
The runnable interface has the following advantages over the inherited Thread class:
(1) It is suitable for multiple threads with the same program code to process the same resource.
(2) avoid restrictions caused by Java single inheritance.
(3) The program robustness is enhanced. The code can be shared by multiple threads, and the code and data are independent.
Therefore, we recommend that you use the runnable interface to implement multiple threads during development.
A thread generally has five states: creation, ready, running, blocking, and termination.
For a Java program, at least two threads must be started each time. One is the main thread and the other is the garbage collection thread.
The lowest priority of a thread; the lowest priority of public static final int min_priority
Public static final int norm_priority medium priority
Public static final int max_priority highest priority
The priority of the main method is norm_priority.
The priority of the main method can be obtained through thread. currentthread (). getpriority ();
PassThread. currentthread (). Yield thread courtesy
You can use both the synchronous code block and the synchronous method to synchronize resources. Keyword synchronized