[JAVA & #183; elementary]: 21. Multithreading
Overview
Program: Program, a static concept
Process: Process is a dynamic concept
A process is a dynamic execution process of a program, occupying a specific address space.
Each process is independent and consists of three parts: cpu, data, and code.
Disadvantages: Memory waste and cpu burden
Thread: Thread, which is a "single continuous control flow" (a single sequential flow ofcontrol)/execution path in the process.
A thread is also called a lightweight process ).
Threads run at the same time, independentlyof one another
A process can have multiple parallel (concurrent) threads
The threads in a process share the same memory unit/memory address space. The workers can access the same variables and objects, and they allocate objects from the same heap to the workers for communication, data exchange, and synchronization operations.
Since inter-thread communication is performed in the same address space, no additional communication mechanism is required, which makes communication easier and Information Transmission faster.
Implementation
The Java. lang. Thread class is responsible for the Thread function in Java.
You can create a Thread by creating an instance of the Thread.
Each Thread performs operations through the method run () corresponding to a specific Thread object. The method run () is called the Thread body.
Start a thread by calling the start () method of Thead class.
Disadvantages of inheriting the Thread class: if our class has been inherited from a class (for example, the Applet must inherit from the Applet Class), the Thread class cannot be inherited.
Multithreading through the Runnable interface
Advantage: inheritance can be implemented at the same time. The method for implementing the Runnable interface must be generic.
Java provides a thread scheduler to monitor all threads in the ready state after the program is started. The thread scheduler determines the thread to be scheduled for execution based on the thread priority.
The thread priority is represented by numbers ranging from 1 to 10.
The default priority of a thread is 5.
Thread. MIN_PRIORITY = 1
Thread. MAX_PRIORITY = 10
Thread. NORM_PRIORITY = 5
Use the following line method to obtain or set the priority of the thread object.
IntgetPriority ();
VoidsetPriority (int newPriority );
Note: low priority only means low probability of obtaining scheduling. It is not a thread that has a higher call priority and a lower call priority.
Demo
public class TestThread2 implementsRunnable { publicstatic void main(String[] args) { Threadthread1 = new Thread(new TestThread2(1));Thread thread2 = new Thread(newTestThread2(2));t1.setPriority(1); t2.setPriority(10);thread1.start(); thread2.start(); } publicvoid run() { for(inti=0;i<100;i++){ System.out.println(this.threadId+":"+i); } }}
Status
New status:
After a Thread object is created with the new Keyword and the Thread class or its subclass, the Thread object is in the new State. A thread in the new State has its own memory space. by calling the start method, it enters the ready state (runnable)
Readiness status:
A thread in the ready state already has the running conditions, but has not been allocated to the CPU. It is in the thread-ready queue and waits for the system to allocate CPU to it. The waiting status is not the execution status. After the system selects a Thread object waiting for execution, it enters the execution status from the waiting status. The action selected by the system is called "cpu scheduling ". Once the CPU is obtained, the thread enters the running state and automatically calls its own run method.
Running status:
In the running state, the thread executes the code in its own run method until other methods are called to terminate, or wait for a resource to block or complete the task and die. If the execution is not completed in the given time slice, the system will change it back to the waiting state.
Blocking status:
A running thread, for example, executes the sleep (sleep) method or waits for resources such as I/O devices, will temporarily stop running the CPU, enter the blocking status. The thread in the blocking status cannot enter the ready queue. Only when the cause of blocking is eliminated, such as the sleep time is reached, or the waiting I/O device is idle, the thread enters the ready state and waits in the ready queue again, after being selected by the system, it starts to run from the stopped position.
Death status:
The dead state is the last stage in the thread lifecycle. There are two causes of thread death. One is that a normal running thread completes all its work, and the other is that the thread is forcibly terminated. For example, the stop or destroy method is executed to terminate a thread. [these two methods are not recommended. The former produces an exception, while the latter forces termination and does not release the lock.
Synchronization and deadlock
As multiple threads of the same process share the same storage space, access conflicts are also a serious problem. The Java language provides a dedicated mechanism to solve this conflict, effectively avoiding the simultaneous access of the same data object by multiple threads.
Because we can use private keywords to ensure that data objects can only be accessed by methods, we only need to propose a mechanism for methods. This mechanism is the synchronized keyword, which includes two usage methods: synchronized Method and synchronized block.
The so-called deadlock refers to the situation where multiple processes are stuck indefinitely while waiting for resources occupied by them. Obviously, without external force, all processes involved in the deadlock will always be blocked. From the above example, we can see that the root cause of the computer system deadlock is limited resources and improper operations. That is, the system provides too few resources to meet the resource requirements of concurrent processes. The deadlock caused by such competitive resources is the core of our discussion. For example, a message is a temporary resource. At A certain time point, process A waits for the message sent by process B, process B waits for the message sent by process C, and process C waits for the message sent by process. When the message is not reached, the processes A, B, and C cannot push forward, and deadlock occurs in Process Communication. Another reason is the deadlock caused by improper process promotion sequence. A deadlock may not occur if there are few resources. Just as if two people crossed the zhuqiao bridge, if both of them had to go over first, and the two were deadlocked and refused to retreat on the zhuqiao, they would inevitably have to compete for resources to create deadlocks. However, if two people first see whether or not they are on the bridge and they are on the bridge when they are on the bridge, the problem will be solved. Therefore, if the program is not properly designed, the process may be pushed in an improper order, and deadlocks may also occur.
Deadlock recovery
Once a deadlock is detected during the Deadlock Detection, it is necessary to eliminate the deadlock and restore the system from the deadlock status.
(1) The simplest and most common method is to restart the system. However, this method is costly, it means that the computing work completed by all previous processes will be done, including those involved in deadlocks and those not involved in deadlocks.
(2) undo the process and deprive the resource. Terminate the processes involved in the deadlock, reclaim the resources they occupy, and then release the deadlock. At this time, there are two situations: cancel all the processes involved in the deadlock at one time, deprive all resources; or gradually withdraw the processes involved in the deadlock, and gradually withdraw the resources occupied by the deadlock process. Generally, the process to be phased out must follow certain principles, with the aim of revoking the processes with the smallest cost, such as determining the cost of the process based on the priority of the process; consider the cost of running processes and the cost of external jobs related to the process.
In addition, there is also a process rollback policy, that is, let the process involved in the deadlock roll back to a point before the deadlock occurs, and continue to execute this point, in order to re-execute the no longer deadlock. Although this is an ideal solution, the system overhead is very high in operating, and it is sometimes impossible to record every step of the process for future rollback.
Task Scheduling
Timer class
TimerTask task class
Through java timer timetask :( spring's task scheduling is implemented through them)
In this implementation method, the Timer class implements a function similar to an alarm clock, that is, to trigger a thread at a scheduled time or at a certain time. In fact, the Timer class implements a thread, but this thread is used to call other threads. The TimerTask class is an abstract class that implements the Runnable interface. Therefore, according to the previous introduction, this class is capable of multithreading.
In this implementation method, the class can obtain the multi-thread capability by inheriting TimerTask, writing the code that requires multi-thread execution inside the run method, and then starting thread execution through the Timer class.
In actual use, a Timer can start any number of threads implemented by TimerTask, but there will be blocking between multiple threads. Therefore, if multiple threads need to run independently, it is recommended that a Timer start a TimerTask implementation.
Business Philosophy
Multi-threaded operations and concurrent execution of independent Instruction Streams make it easy for users.
This section describes all aspects of Java multi-threaded programming, including creating threads and scheduling and management of multiple threads. A profound understanding of the complexity of multi-threaded programming and the inefficiency of multi-threaded programs brought about by thread switching overhead also prompted us to seriously consider the question: do we need multithreading? When do I need multithreading?
The core of multithreading lies in the concurrent execution of multiple code blocks. The essential feature is that the Code between different code blocks is executed in disorder. Whether or not our program requires multithreading depends on whether it is also its internal characteristic.
If our program does not require concurrent execution of multiple code blocks, we naturally do not need to use multithreading. If our program requires concurrent execution of multiple code blocks, we do not need to execute them in disorder, we can use a loop to implement it in a simple and efficient way without using multithreading. Only when it fully complies with the characteristics of multithreading, the strong support of the multithreading mechanism for inter-thread communication and thread management can be used. It is worthwhile to use multithreading.