The basic concept

The concept of programs and processes

  • Programs – data structures + algorithms, mainly executable files stored on hard disk.
  • Processes – Mainly executable files running 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.

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.

Thread creation

The concept of Thread classes

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

Create a way

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

Related methods

Method statement Function is introduced
Thread() Constructs objects without arguments
Thread(String name) Constructs the object from the name specified by the argument
Thread(Runnable target) Constructs an object from the reference specified by the argument, where Runnable is an interface type
Thread(Runnable target, String name) An object is constructed by specifying a reference and name as parameters
void run() If a thread object is constructed using a Runnable reference, calling this method ends up calling the version in the interface

If a thread object is not constructed using a Runnable reference, nothing is done when this method is called
void start() Used to start a thread, the Java virtual machine automatically calls the run method of that thread

Execute the 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.

Comparison of ways

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

Anonymous inner class

  • Use anonymous inner classes to create and start threads.

The life cycle of a thread

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

The thread number and name

Method statement Function is introduced
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/modifies the thread name to the value specified by the argument
static Thread currentThread() Gets a reference to the currently executing thread

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(times) 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 isDaemon() Used to determine whether it is a daemon thread
void setDaemon(boolean on) Used to set a thread to be a daemon 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 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 reference) {// Write all the code that needs to be locked;
}
Copy the code
  • Lock all code using synchronous methods.

    Simply use the synchronized keyword to modify the entire method

    This method is equivalent to:

    Synchronized (this) {synchronized(this)

Locking of static methods

  • When we lock a static method, as in:

    Public synchronized static void XXX (){... }
  • 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.

Matters needing attention

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

Thread-safe and unsafe classes

  • The StringBuffer class is thread-safe, but the StringBuilder class is not thread-safe.
  • 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.

The concept of deadlock

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

Use locks to synchronize threads

The basic concept

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

Common methods

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

Comparison with synchronized

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

A common method of the Object class

Method statement Function is introduced
void wait() Used to make a thread wait until another thread calls notify() or notifyAll()
void wait(long timeout) 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

The thread pool

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

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

The origin of thread pools

  • 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 the performance of the server.

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.

Related classes and methods

  • Starting from Java 5 provides a thread pool of related classes and interfaces: Java. Util. Concurrent. The Executors and Java. Util. Concurrent. The ExecutorService interface.
  • You can create and return different types of thread pools by following the following methods:
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 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