1 Basic Concepts

1.1 Concepts of procedures and processes

  • Procedure: data structure + algorithm, mainly refers to the executable file stored on the hard disk.
  • Process: Mainly refers to the executable file that runs in memory.
  • At present, mainstream operating systems support multiple processes. To enable the operating system to perform multiple tasks at the same time, however, processes are heavyweight. That is, creating a process consumes system resources such as CPU and memory space, so the number of processes is limited.

1.2 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 uses time slice rotation method to ensure the concurrent execution of multiple threads, the so-called concurrency refers to the macro parallel micro serial mechanism.

2 Thread creation

2.1 Concept of Th read class

  • 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.

2.2 Creation Mode

  • The custom class inherits the Thread class and overwrites the run method, then creates an object of the class that calls the start method.
  • The custom class implements the Runnable interface and overwrites the run method, creates an object of the class as an argument to construct an object of type Thread, and then calls the start method with an object of type Thread.

2.3 Relevant methods

Method statement Function is introduced
Thread() Constructs objects without arguments
Thread(String nam e) Constructs the object from the name specified by the argument
Thread(Runnable target) An object is constructed from a reference specified by the argument, where type Runnable is an interface class
Thread(Runnable target,
String nam e) An object is constructed by specifying a reference and name as parameters
void run() If a thread object is constructed using a Runnable reference, the method ends up calling the version in the interface. If the thread object is not constructed using a Runnable reference, the method does nothing
void start() Used to start a thread, the Java virtual machine automatically calls the run method of that thread

2.4 Execution Process

  • The thread that executes main is called the main thread, and the thread that executes run is called the new thread/child thread.
  • The main method is the entry of the program, for the code before the start method, by the main thread to execute once, when the start method successfully called the number of threads from 1 to 2, the new started thread to execute the code of the run method, the main thread continues to execute, the two threads run independently without affecting 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.

2.5 Comparison of methods

  • However, if the class inherits Thread, it cannot inherit other classes. However, if the class implements Runnable interface, the code is complex, but it does not affect the class inheriting other classes and implementing other interfaces. Therefore, the second method is recommended for future development.

2.6 Anonymous inner class approach

  • Use anonymous inner classes to create and start threads.

3 The life cycle of threads

  • New state – The state entered after being created with the new keyword before the thread starts executing.

  • Ready state – The state entered after the start method is called, but the thread has not yet started execution.

  • Running State – The state entered after the thread is called using the thread scheduler, when the thread begins to execute, and returns to ready state if the task is not completed after the thread’s time slice has completed.

  • Dead state – The state entered by a thread when its task has been completed, and the thread is terminated.

  • Blocking state – A state entered when a blocking event occurs during thread execution, such as the sleep method. Enter the ready state after the blocking state is cleared.

4 Number and name of the thread

Method statement Function is introduced
long getId() Gets the number of the thread represented by the calling object
String getNam e() Gets the name of the thread represented by the calling object
void setNam e(String nam e) Sets/modifies the thread name to the value specified by the argument
static Thread currentThread() Gets a reference to the currently executing thread

5 Common methods

Method statement Function is introduced
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(tim es) InterruptedException occurs if another thread interrupts the current thread’s Block(sleep).
int getPriority() Gets the priority of the thread
void setPriority(int newPriority) 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
void join(long millis) The number of milliseconds to wait for the parameter specified
boolean isDaem on() Used to determine whether it is a daemon thread
void setDaem on(boolean on) Used to set a thread to be a daemon thread

6 Thread synchronization mechanism

6.1 Basic Concepts

  • 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.

6.2 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.
  • Conclusion: In future development, minimize the scope of serial operations to improve efficiency.

6.3 Implementation Methods

The synchronized keyword is used in the Java language to implement the synchronization/object locking mechanism to ensure atomicity of thread execution, as follows:

  • Part of the code is locked by synchronizing code blocks in the following format:
synchronized(class type references) {write all the code that needs to be locked; }Copy the code
  • Lock all code using synchronous methods.

Use the synchronized keyword to modify the method as follows:

synchronized(this) {whole method body code}Copy the code

6.4 Locking static methods

  • When we lock a static method, as in:
public synchronized static void xxx(a){... .}Copy the code
  • Then the object that the method locks is a class object. Each class has a unique class object. How to get class objects: class name.class.
  • Both static and non-static methods are non-exclusive when synchronized is used.
  • The reason is that static methods lock class objects rather than static methods lock the object to which the current method belongs.

6.5 Precautions

  • Use synchronized to ensure thread synchronization:
    • 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.

6.6 Thread-Safe and Unsafe Classes

  • The StringBu o ffer class is thread-safe, but the StringBuilder class is not.
  • The Vector and Hashtable classes are thread-safe, but the ArrayList and HashMap classes are not.
  • The Collections. SynchronizedList () and the Collections. SynchronizedMap () method to implement security.

6.7 Deadlock concepts

  • Thread 1 executes the code:
public void run(a){
synchronized(a){	// Hold object lock A and wait for object lock B
synchronized(b){write locking code; }}}Copy the code

Thread 2 executes code:

public void run(a){
synchronized(b){	// Hold object lock B and wait for object lock A
synchronized(a){write locking code; }}}Copy the code

Note:

In future development, try to reduce synchronized resources and reduce the use of nested structures of synchronized code blocks!

6.8 Using Lock to Synchronize Threads

(1) Basic concepts

  • Starting with Java5, a more powerful thread synchronization mechanism is provided – implemented 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.

(2) Common methods

Method statement Function is introduced
ReentrantLock() Constructs objects with no arguments
void lock() Acquiring a lock
void unlock() Release the lock

(3) Comparison with synchronized method

  • Lock is an explicit Lock that needs to be manually opened and closed, while synchronized is an implicit Lock that is automatically released after the locking code is executed.
  • Lock has only synchronized block locks, while synchronized has both block and method locks.
  • With Lock, the Java VIRTUAL machine takes less time to schedule threads and therefore performs better.

6.9 Common methods of the Object class

Method statement Function is introduced
void wait() Used to make a thread wait until the notify() or notifyAll() methods are called by other threads
void wait(longtim eout) Used to enter the wait state until the number of milliseconds specified by another thread calling a method or argument has elapsed
void notify() Used to wake up a single thread waiting
void notifyAll() Used to wake up all waiting threads

6.10 the thread pool

(1) Implement Callable interface

Increased from Java 5 to start create a thread of the third way to implement Java. Util. Concurrent. Callable interface. The common methods are as follows:

Method statement Function is introduced
V call() Compute the result and return it

(2) FutureTask class

Java. Util. Concurrent. FutureTask classes are used to describe cancelable asynchronous computation, the class provides the basic implementation of Future interface, including the start and cancel, query calculation is completed and the method of retrieval results, can also be used to access after the method invocation returns the result. The common methods are as follows:

Method statement Function is introduced
FutureTask(Callable callable) Creates a future task based on the reference specified by the parameter
V get() Gets the result of the call method calculation

(3) Origin of 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, for each client connection, the server creates a new thread.

  • If there are many clients accessing the server, the server is constantly creating and destroying threads, which can seriously affect server performance

Can.

(4) Concepts and principles

  • The concept of thread pool: first create some threads, their collection is called thread pool, when the server receives a client request, it takes out a free thread from the thread pool to serve it, after the service is finished, it does not close the thread, but returns the thread to the thread pool.

  • Programming mode, the task of the thread pool is submitted to the thread pool, rather than directly to a thread, the thread pool, after to get the task it internally to find any spare threads, then give the task to a free thread, internal task is submitted to the thread pool, a thread can only perform one task at the same time, but it can be submitted to a thread pool multiple tasks at the same time.

(5) Related classes and methods

  • Starting from the Java 5 provides a thread pool related classes and interfaces: Java. Util. Concurrent. The Executors and class

Java. Util. Concurrent. The ExecutorService interface.

  • Executors is a factory class for tools and thread pools. You can create and return different types of thread pools using the following methods

Bottom:

Method statement Function is introduced
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 threads
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. The common methods are as follows:

Method statement Function is introduced
void execute(Runnable com mand) Performs tasks and commands, usually used to perform Runnable
Future subm it(Callable task) Performs tasks and commands, typically for Callable execution
void shutdown() Start orderly shutdown