Multithreading Benefits in Java
is to cancel the main loop/polling mechanism. A thread pause does not affect other parts of the program. The idle time that is generated by a thread during an operation (user input, reading network data) can be exploited elsewhere.
Thread state
Running (Running)-to-suspend (Suspend)-Resume (resume)-and-terminate (terminate).
Note: Threads can run as long as they get CPU time. The thread temporarily interrupts after suspending, allowing the recovery to be resumed where it was interrupted. Once a thread terminates, it cannot be restored.
Wait (): tells the called thread to discard the incoming pipe, go to sleep until another thread enters the same pipe, and call Notify ().
Notify (): Restores the same object the first call to wait () on a thread.
Notifyall (): Restores all of the wait () threads in the same object, with the highest priority running first.
The above three methods can only be called in the Synchronize method.
Creating threading Methods in Java
There are two ways to create a thread. 1. Inherit thread class 2, implement Runnable interface
Inherit the thread class
The method must override the run () method and define the tasks that need to be implemented in the run () method.
After creating the thread object, call the Start () method to start the thread. Note that instead of calling the run () method to start the thread, the Run method simply defines the task that needs to be performed, and if calling the Run method, which is equivalent to executing the Run method in the main thread, is no different from the normal method call, and does not create a new thread to perform the defined task.
If different thread objects call the run () and start () methods, the Start () method as a new thread does not block the run () method as a follow-up to the main thread.
Implementing the Runnable Interface
By implementing the Runnable interface, a subtask is defined, and then the subtasks are assigned to thread for execution. Note that this method must use runnable as the parameter of the thread class, and then create a new thread to execute the subtask by using the thread's Start method. If you call Runnable's Run method, you will not create a new thread, and this common method call is no different.
Summary of "multithreading" basics