I. Concepts of threads and processes
The current operating system is a multi-task operating system. Multithreading is a way to implement multiple tasks.
A process is a dynamic execution process of a program. It refers to an application running in the memory. Each process has its own memory space and multiple threads can be started in a process. For example, in Windows, a running exe is a process. A thread is an execution process in a process. A process can run multiple threads. For example, a Java. EXE process can run multiple threads. A thread always belongs to a process. Multiple threads in the process share the memory of the process. "At the same time" execution is a human perception, and is actually rotated between threads.
II. Implementation of threads in Java
There are two methods to implement multithreading in Java. One is to integrate the Thread class, and the other is to implement the Runnable interface. The following describes how to create a Thread inherited from the Thread class.
First, define a Thread class, which must inherit from the Thread class and overwrite the run () method explicitly, such:
Class MyThread extends Thread {
Public void run () {// override the run method in the Thread class. This method is in the Thread
Thread subject;
}
}
Define a main class, instantiate the object of the thread class, and start the thread command, such:
Public class ThreadText {
Public stataic void main (String args []) {
MyThread m1 = new MyThread (); // instantiate an object
M1.start (); // start multiple threads
}
}
To implement the Runnable interface, first define a thread class to inherit from the Runnable interface, such:
Class MyThread implements Runnable {
Public void run () {// override the run method in the Runnable interface
Thread subject;
}
}
Define a main class, instantiate the object of the thread class, and start the thread command, such:
Public class ThreadText {
Public stataic void main (String args []) {
MyThread m1 = new MyThread (); // instantiate the Runnable subclass object
Thread t1 = new Thread (m1); // instantiate a Thread class object
T1.start (); // start multiple threads
}
}
III. Several states of threads
In Java, threads generally have five states: Creation, readiness, running, blocking, and death.
The first is the creation status. When a thread object is generated, the start method of the object is not called, which is the thread being created.
The second is readiness. After the start method of the thread object is called, the thread enters the ready state, but the thread scheduler has not set the thread as the current thread, and is in the ready state. After the thread is running, it will also be ready after it comes back from waiting or sleep.
The third is the running status. The thread scheduler sets the ready thread to the current thread. The thread enters the running state and starts running the code in the run function.
The fourth is the blocking status. When the thread is running, it is paused, usually to wait for a certain time (for example, a resource is ready) before running. Sleep, suspend, wait and other methods can cause thread blocking.
Fifth, death. If the run method of a thread ends or the stop method is called, the thread will die. For dead threads, you cannot use the start method to make them ready.
ThreadLocal multi-threaded java applications
ThreadLocal is easy to understand and take for granted as a "local Thread ". In fact, ThreadLocal is not a Thread, but a local variable of the Thread. It may be easier to understand to name it ThreadLocalVariable. When ThreadLocal is used to maintain a variable, ThreadLocal provides an independent copy of the variable for each thread that uses the variable. Therefore, each thread can change its own copy independently, it does not affect the copies corresponding to other threads.
First, ThreadLocal is not used to solve the problem of multi-threaded access to shared objects. Generally, ThreadLocal is used. the objects from set () to the thread are the objects used by the thread. Other threads do not need to be accessed or cannot be accessed. Different threads access different objects.
In addition, ThreadLocal enables each thread to maintain an independent object instead of ThreadLocal. set () is implemented, but through the operation of the new object in each thread. Each thread creates one object, not a copy or copy of the object. Through ThreadLocal. set () saves the reference of the newly created object to a map of each thread. Each thread has such a map and runs ThreadLocal. in get (), each thread extracts the objects from its own map, so it obtains the objects in its own thread, and the ThreadLocal instance is used as the map key.
If ThreadLocal. set () is the same object shared by multiple threads, so ThreadLocal of multiple threads. get () still gets the shared object itself, but there are still concurrent access problems.
JDK 5 and later provide generic support. ThreadLocal is defined as generic:
Public class ThreadLocal <T> extends Object
T is the type of the local variable of the thread. This class defines four methods:
1) protected T initialValue (): returns the "initial value" of the current thread of the local variable of this thread ". This method is called when the thread uses the get () method to access the variable for the first time. However, if the thread previously called the set (T) method, it will not call the initialValue method for this thread. Generally, this method can be called at most once for each thread, but if remove () is called again after get () is called, this method may be called again. This implementation returns null. If a programmer wants a local variable of a thread to have a value other than null, the programmer must create a subclass for ThreadLocal and override this method. The anonymous internal class is usually used to complete this operation.
2) public T get (): return the value in the current thread copy of the local variable of this thread. If the variable is not used for the value of the current thread, initialize it to the value returned by calling the initialValue () method.
3) public void set (T value): set the value in the current thread copy of the local variable of this thread to the specified value. Most subclasses do not need to override this method. They only rely on the initialValue () method to set the value of the local variable of the thread.
4) public void remove (): removes the value of the current thread of the local variable of this thread. If the local variable of this thread is subsequently read by the current thread and the current thread does not set its value during this period, the initialValue () method will be called to reinitialize its value. This causes the initialValue method to be called multiple times in the current thread.
The following example uses ThreadLocal. Each thread generates its own serial number. This means that ThreadLocal is used to store copies of independent serial numbers of each thread. Threads do not interfere with each other.
Package sync;
Public class SequenceNumber {
// Define the variable for creating ThreadLocal in the anonymous subclass
Private static ThreadLocal <Integer> seqNum = new ThreadLocal <Integer> (){
// Overwrite the initialization method
Public Integer initialValue (){
Return 0;
}
};
// The next serial number
Public int getNextNum (){
SeqNum. set (seqNum. get () + 1 );
Return seqNum. get ();
}
Private static class TestClient extends Thread {
Private SequenceNumber sn;
Public TestClient (SequenceNumber sn ){
This. sn = sn;
}
// The serial number generated by the thread
Public void run (){
For (int I = 0; I <3; I ++ ){
System. out. println ("thread [" + Thread. currentThread (). getName () + "] sn [" + sn. getNextNum () + "]");
}
}
}
/**
* @ Param args
*/
Public static void main (String [] args ){
SequenceNumber sn = new SequenceNumber ();
// Three threads generate their respective serial numbers
TestClient t1 = new TestClient (sn );
TestClient t2 = new TestClient (sn );
TestClient t3 = new TestClient (sn );
T1.start ();
T2.start ();
T3.start ();
}
}
The program running result is as follows:
Thread [Thread-1] sn [1]
Thread [Thread-1] sn [2]
Thread [Thread-1] sn [3]
Thread [Thread-2] sn [1]
Thread [Thread-2] sn [2]
Thread [Thread-2] sn [3]
Thread [Thread-0] sn [1] thread [Thread-0] sn [2]
Thread [Thread-0] sn [3]
The running results show that with ThreadLocal, each thread generates an independent serial number without mutual interference. We usually define ThreadLocal subclass through anonymous internal classes to provide initial variable values.
What are the advantages of ThreadLocal over thread synchronization? ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict between the same variables in multiple threads.
In the synchronization mechanism, the object lock mechanism ensures that only one thread accesses the variable at a time. At this time, the variable is shared by multiple threads. The synchronization mechanism requires the program to carefully analyze when to read and write the variable, and when to lock an object, when to release the object lock and other complicated issues, it is relatively difficult to design and write the program. ThreadLocal solves multi-thread concurrent access from another perspective. ThreadLocal provides an independent copy of variables for each thread, thus isolating multiple threads from access conflicts to data. Because every thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, you can encapsulate insecure variables into ThreadLocal.
To sum up, for multi-threaded resource sharing, the synchronization mechanism adopts the "time for space" approach, while ThreadLocal adopts the "space for time" approach. The former provides only one copy of the variable, allowing different threads to queue for access, while the latter provides a copy of the variable for each thread. Therefore, the former can be accessed simultaneously without affecting each other.
It should be noted that the ThreadLocal object is a tool with risks in nature. You should use the ThreadLocal object after fully understanding the thread model to be used. This leads to the thread pool (thread pooling) problem. The thread pool is a thread reuse technology. With the thread pool, it is not necessary to create a new thread for each task, A thread may be used multiple times. Any ThreadLocal object used in this environment contains the state set by the code of the last thread, it is not the state that is not initialized when the new thread is started. How does ThreadLocal store copies of independent variables for each thread? By viewing its source code, we will find that the current "thread object" is used as the key, and the variable as the value is stored in a Map.
Private T setInitialValue (){
T value = initialValue ();
Thread t = Thread. currentThread ();
ThreadLocalMap map = getMap (t );
If (map! = Null)
Map. set (this, value );
Else
CreateMap (t, value );
Return value;
}
In short, ThreadLocal is not used to solve the problem of shared object access, but mainly provides methods to keep objects and convenient object access methods to avoid passing parameters. Two points are summarized:
1. Each thread has its own ThreadLocalMap class object, which can keep the thread's own objects in it. The thread can correctly access its own objects in various tubes.
2. Use a shared ThreadLocal static instance as the key, save the references of different objects to ThreadLocalMap of different threads, and then run get () of the static ThreadLocal instance everywhere () method to get the object saved by the thread, avoiding the trouble of passing this object as a parameter.
Of course, if you want to pass the thread-shared object through ThreadLocal. set () can also be placed in the thread to avoid the access method passed by parameters. However, note that get () is the same shared object, concurrent access problems must be solved by other means. But in general, the objects shared by the thread can be easily accessed by setting them to a certain type of static variables. It seems that there is no need to put them in the thread.
In the application scenario of ThreadLocal, I think it is best to access objects with multiple threads (each thread corresponds to an instance), and this object is used in many places.
Some of the above materials are self-written, some are based on others', and then modified by themselves. If you have any questions during your learning, you can also raise them here.