The basic concept

The concept of program and process

  • Procedure: data structure + algorithm, mainly refers to the executable file stored on the hard disk
  • Process: An executable file running in memory
  • At present, the mainstream operating system supports multi-process, in order to make the operating system can execute multiple files at the same time. However, processes are heavyweight, meaning that creating a process consumes system resources such as CPU and memory space, so the number of processes is relatively limited

The concept of threads

  • In order to solve the above problem, puts forward the concept of threads, thread is the internal program flow process, meaning that the operating system supports multiple internal process, and each process of the internal support multithreading, thread is a lightweight, new threads will be Shared in the process of system resources, therefore the current mainstream development are using multithreading
  • Multithreading is to use the time slice wheel method for the concurrent execution of multiple threads, the so-called concurrency refers to the macro parallel micro serial mechanism

Thread class

concept

  • The java.lang.Thread class represents threads, and any Thread object is an instance of the Thread class (subclass)
  • The Thread class is a template for threads, encapsulating complex operations such as Thread startup and encapsulating the differences of operating systems

Basic method

methods function
Thread() Build the object
Thread(String name) Specifies the thread name to build the object
Thread(Runnable target) Specify the object of the Runnable interface to build the object
Thread(Runnable target,String name) Specify the thread name and object to build the object
void run() If a thread object is built using a Runnable reference, calling this method is the version in the final call interface

If the thread object is not built using a Runnable reference, nothing is done when the method is called
void start() When the thread is started, the JVM automatically calls the run() method

Thread creation

  • Method 1: The custom class inherits Thread and overwrites the run() method, then creates an instance and calls the start() method.
  • Approach 2: The custom class implements the Runnable interface and overwrites the run() method, then creates instances and uses them as arguments to build objects of type Thread, and then calls the Start () method of Thread.
// Method 1:
new Thread(){
    @Override
    public void run(a){
    // Override the method
    }
}.start();
/ / way 2:
new Thread(new Runnable(){
	@Override
    public void run(a){
    // Override the method
    }
}).start();
Copy the code

Execute the process

  • The thread that executes main is called the main thread, and the thread that executes run is called the child thread/new thread
  • The main method is the entry of the program, for the code before the start method, there is a main thread to execute once, when the start method is called successfully, the number of threads from 1 to 2, the newly started thread to execute the run method, the main thread continues to execute, the two threads run independently of each other
  • The child thread ends when the run method completes, and the main thread ends when the main method completes
  • There is no clear order of execution between the two threads, which is determined by the operating system scheduling algorithm

The declaration cycle of a thread

  • New state: The state entered after using the new keyword keyword before the thread has started execution
  • Ready state: the state entered after the start method is called, while the thread has not yet started execution
  • Running state: The state entered after a thread is called using the thread scheduler, at which point the thread begins to execute, and returns to the ready state if the task is not completed after the thread’s time segment completes
  • Dead state: The state entered by a thread when its task has been completed, and the thread is terminated
  • Blocked state: The state that a thread enters when a blocking event occurs during execution, such as the sleep method, and enters the ready state when the blocking state is cleared

Common methods of the Thread class

methods function
static void yield() The current thread leaves the processor (out of the Running state), making the current thread wait in the Runnable state
static void sleep(int ms) The current thread abandons the processor from the Running state into the Block state, sleeps for ms milliseconds,

Return to Runnable, which occurs if another thread interrupts the current thread’s Block(sleep)

InterruptedException
int getPriority() Gets the priority of the current thread
void setPriority(int priority) Example Change the priority of a thread

The thread with a higher priority may not execute first, but it has a better chance of getting the time slice
void join() Wait for the thread to terminate (indicates that the currently executing thread object is waiting to call the thread object)
void join(long millis) The number of milliseconds specified by the wait argument (indicates that the currently executing thread object is waiting to call the thread object, up to millis)
boolean isDaemon() Used to determine whether it is a daemon thread
void setDaemon(boolean on) Used to set the thread to daemon (must be set before start() is called)
long getId() Gets the number of the thread represented by the calling object
String getName() Gets the name of the thread represented by the calling object
void setName(String name) Sets the name of the thread represented by the calling object
static Thread currentThread() Gets the application of the current thread

Thread synchronization mechanism

The basic concept

  • When multiple threads access the same shared resource at the same time, data coverage and other inconsistent problems may be caused. In this case, communication and coordination between threads are required. This mechanism is called thread synchronization mechanism
  • Thread concurrency safety issues occur when multiple threads concurrently read and write to the same critical resource
  • Asynchronous operation: Multi-threaded concurrent operation, each run independently
  • Synchronous operations: multi-threaded sequential operations, the order in which they are executed

The solution

  • According to the results of the program, when two threads withdraw from the same account at the same time, the final account balance is unreasonable
  • Cause: Thread two has already started to withdraw money before thread two can write the balance after withdrawal into the background
  • Solution: let thread one complete the withdrawal operation, and then let thread two can execute, change the concurrent operation of the thread to serial operation
  • Experience sharing: In the future development, try to reduce the scope of serial operation, so as to improve efficiency

implementation

  • The Synchronized keyword is used in the Java language to implement the synchronization/object locking mechanism. Thus ensuring thread executionatomic, the specific methods are as follows:
  • Atomicity: Represents operations that are minimized, either completed or not performed, and cannot be interrupted.
// Lock part of the code by synchronizing the code block
synchronized(/* References to class types */) {}// Require a reference to the same object
// Lock all code using synchronous methods
synchronized void test(a){}
/ / equivalent to the
void test(a){
    synchronized(this){}
}
Copy the code

Locking of static methods

  • When we lock a static method, as in:public synchronized static void test(){};Each class has a unique class object. The method to obtain the class object is named.class
  • When synchronized is used in a static method and a non-static method, the relationship between them is not mutually exclusive. The reason is that the static method locks the class object, while the non-static method locks the object to which the current method belongs
public synchronized static void test(a){};
/ / equivalent to the
void test(a){
    synchronized(Class name.class){}}Copy the code

Precautions of synchronized

  • Multiple threads that need to synchronize should see the same lock object reference when accessing a synchronized block.
  • When using synchronized blocks, the synchronization scope should be minimized to improve the efficiency of concurrent execution

Use Lock for thread synchronization

The basic concept

  • Starting with Java 5, a more powerful thread synchronization mechanism is available using explicitly defined synchronization lock objects
  • Java. Util. Concurrent. The locks. Lock interface is the tool of control multiple threads to Shared resources access
  • The main implementation class of this interface is the ReentrantLock class, which has the same concurrency as synchronized and is often used to explicitly lock and release locks in future thread-safe control

Commonly used method

methods function
ReentrantLock() Construct object
void lock() locked
void unlock() Release the lock

Compared with the synchronized

Lock synchronized
type The explicit lock Implicit lock
operation Manually open and close Automatic release after code execution
Work way Synchronized code block lock Synchronized code block locks and synchronized method locks
performance Better performance Slower than Lock mode

Thread synchronization method in the Object class

methods function
void wait() Used to make a thread wait until another thread calls notify() or notifyAll(), which releases the lock
void wait(long timeout) Enters the wait state until the time specified by the argument passes or another thread calls the method
void notify() Wake up a waiting single thread
void notifyAll() Wake up all waiting threads

The thread pool

Callable interface

  • A third way to create threads has been added since Java 5: implementing the Callable interface
  • Callable threads return values

FutureTask class

  • Used to describe cancelable asynchronous computations. This class provides the basic implementation of the Future interface, including methods to start and cancel computations, query whether a computation is complete, and retrieve the result of a computation, as well as to get the return result of a method call

The thread pool

  • In the principle of the server programming model, each client connection is served by a separate thread. When the session with the client ends, the thread ends. That is, the server creates a thread for each client connection
  • If there are many clients accessing the server, the server is constantly creating and destroying threads, which can seriously affect the performance of the server
  • What is a thread pool? When a server receives a client request, it takes an idle thread from the thread pool to serve it. Instead of closing the thread, it returns it to the thread pool
  • In the thread pool programming mode, tasks are submitted to the entire thread pool, rather than directly to a single thread. After the thread pool gets the task, it finds a free thread and then gives the task to the free thread. A thread can only perform one task at a time, but can submit multiple tasks to a thread pool at the same time

Java 5 provides thread pool-related classes and interfaces: Executors and ExecutorService interfaces

  • Executors is an engineering class for tools and thread pools that can create and return different types of thread pools
    methods function
    static ExecutorService newCachedThreadPool() Create a thread pool that can create new threads as needed
    static ExecutorService newFixedThreadPool(int nThreads) Create a reusable thread pool with a fixed number of thread pools
    static ExecutorService newSingleThreadExecutor() Create a thread pool with only one thread
  • The ExecutorService interface is the real thread pool interface, and the main implementation class is ThreadPoolExecutor
    methods function
    void execute(Runnable command) Performs tasks and commands, usually used to perform Runnable
    Future submit(Callable task) Performs tasks and commands, typically for Callable execution
    void shutdown() Start orderly shutdown