Java multi-thread ultra-Detailed summary-Alibaba Daniel stayed up late, Alibaba Daniel

Source: Internet
Author: User
Tags finally block

Java multi-thread ultra-Detailed summary-Alibaba Daniel stayed up late, Alibaba Daniel
Introduction

If you are still confused about what a thread is and what a process is, Google the two concepts, because they are not within the scope of this article.

Multithreading has only one purpose, that is, to make better use of cpu resources, because all multithreaded code can be implemented using a single thread. In fact, this is only half right. Because the program code that reflects "multiple roles", at least each role should give him a thread. Otherwise, the actual scenario cannot be simulated, of course, it cannot be said that it can be implemented using a single thread: for example, the most common "producer and consumer model ".

Many people are not clear about some of these concepts, such as synchronization and concurrency. Let's create a data dictionary first to avoid misunderstanding.

  • Multithreading: This program (a process) runs with more than one thread.
  • Concurrency and concurrency:
  • Parallel: multiple cpu instances or multiple machines execute a processing logic at the same time.
  • Concurrency: the cpu scheduling algorithm allows users to execute simultaneously. In fact, the cpu operation level is not actually the same. Concurrency usually involves public resources in scenarios, so there is often a bottleneck for this public resource. We will use TPS or QPS to reflect the processing capability of this system.
Concurrency and Parallelism
  • Thread security: often used to depict a piece of code. In the case of concurrency, the code is used in multiple threads, and the scheduling sequence of threads does not affect any results. When multithreading is used, we only need to pay attention to the system memory. Is the cpu enough. In turn, thread insecurity means that the scheduling order of the thread will affect the final result. For example, if the transaction transfer code is not added:
  • Synchronization: synchronization in Java means that through human control and scheduling, multi-threaded access to shared resources becomes thread-safe to ensure accurate results. The code above is simply added@synchronizedKeyword. It is an excellent program to improve performance while ensuring accurate results. Thread security has a higher priority than performance.

Okay. Let's get started. I am going to divide it into several parts to summarize the content involving multithreading:

Tie up the horse step: thread status

Let's take two pictures first:


Various statuses are clear at a glance. It is worth mentioning the differences between the "Blocked" and "Waiting" statuses:

  • The thread may encounter Blocked during the Running process.
    Apply a synchronization lock (Synchronized) to a thread in the Running state to enter the lock blocked pool. The synchronization lock is released and enters the Runnable state ). From the jdk source code comment, blocked refers to the waiting for monitor (you can refer to the figure below), that is, the thread is located in the waiting area.

  • The thread may encounter Waiting during the Running process.
    A thread can actively call object. wait or sleep, or join (The join Operation calls sleep internally, so it can be considered as a sleep. From the jdk source code comments, waiting is waiting for another thread to complete an operation, such as join waiting for another execution to complete, and object. wait () waiting for the object. Y () method to be executed.

Waiting status and Blocked statusI personally understand that Blocked is actually a kind of wait, Waiting for monitor, but in a different status than Waiting. For example, three threads enter the synchronization block, two of them call the object. wait (), enters the waiting state, and the third calls the object. notifyAll (). At this time, one of the first two threads is transferred to Runnable, and the other is transferred to Blocked.

Different from the monitor structure diagram below: Each Monitor can only be owned by one Thread at a specific time. This Thread is "Active Thread", while other threads are "Waiting Thread ", wait in the "Entry Set" and "Wait Set" Queues respectively. Blocked is the thread status Waiting in the "Entry Set". In the dump of jstack, it is "Waiting for monitor entry", while in the "Wait Set", the Waiting thread status is Waiting, it is represented in the dump of jstack as "in Object. wait ()".

In addition, a thread in the runnable state is in the scheduling thread, and the scheduling order is not certain at this time. The yield method in the Thread class allows a running Thread to be transferred to runnable.

Internal power method: method (mechanism) available for each object)

Synchronized, wait, and y are synchronization tools available to any object. Let's get to know them first

 

They are artificial thread scheduling tools used for synchronization issues. To understand its essence, we must first clarify the concept of monitor. Every object in Java has a monitor to monitor the re-entry of concurrent code. This monitor does not play a role in non-multi-thread encoding. If it is within the synchronized range, the monitor plays a role.

Wait/notify must exist in the synchronized block. In addition, these three keywords target the same Monitor (the monitor of an object ). This means that after wait, other threads can enter the synchronization block for execution.

When a Code does not have the right to use the Monitor (the status of medium 5, that is, the synchronization block) to go to wait or ipvy, java. lang. IllegalMonitorStateException will be thrown. It also includes calling wait/notify of another object in the synchronized block. This exception is thrown because the monitors of different objects are different.

Let's talk about the usage:

  • Synchronized is used separately:
  • Code block: as follows: In a multi-threaded environment, the synchronized block method obtains the monitor of the lock instance. If the instance is the same, only one thread can execute the block content.
  • Directly used for the method: equivalent to the effect of locking with lock in the code above, the actual result is the Thread1 class monitor. Furthermore, if the static method is modified, all instances of this class will be locked.
  • Synchronized, wait, and consumer y are combined: producer and consumer problems in typical scenarios.
/*** Give the product produced by the producer to the clerk */public synchronized void produce () {if (this. product> = MAX_PRODUCT) {try {wait (); System. out. println ("the product is full, please reproduce it later");} catch (InterruptedException e) {e. printStackTrace ();} return;} this. product ++; System. out. println ("producer production" + this. product + "product. "); policyall (); // notify the consumer in the waiting area to retrieve the product}/*** the consumer obtains the product from the clerk */public synchronized void consume () {if (this. product <= MIN_PRODUCT) {try {wait (); System. out. println ("out of stock, get again later");} catch (InterruptedException e) {e. printStackTrace ();} return;} System. out. println ("the consumer took the first" + this. product + "product. "); this. product --; yyall (); // notification that the producer waiting to go can produce the product}
Volatile

Multi-threaded memory Model: main memory (main memory) and working memory (thread stack). When processing data, the thread will load the value from the main memory to the local stack, after the operation is completed, save it back (Role of the volatile Keyword: load and save are triggered every operation on the variable ).

 

Variables used for multithreading, if not modified by volatile or final, may produce unpredictable results (another thread modifies this value, but what we will see later in a thread is the value before the modification ). In fact, the same attribute of the same instance has only one copy. However, multithreading caches the value. In essence, volatile does not cache the value directly. Adding volatile to thread security sacrifices performance.

Taizu Changquan: Basic Thread class

The basic Thread class refers to the Thread class, Runnable interface, and Callable interface.
The Thread class implements the Runnable interface to start a Thread:

Thread-related methods:

About interruptions: It does not interrupt a running thread like the stop method. The thread checks the interrupt Identifier from time to determine whether the thread should be interrupted (whether the interrupt Identifier value is true ). The terminal only affects the wait Status, sleep status, and join status. The interrupted thread will throw InterruptedException.
Thread. interrupted () checks whether the current Thread is interrupted and returns a boolean value.
Synchronized cannot be interrupted during the lock process.

Interruption is a status! The interrupt () method only sets this status to true. Therefore, normal programs will not terminate without detecting the status, and wait and Other blocking methods will check and throw an exception. If you add while (! Thread. interrupted (), you can also leave the code body after the interruption

Thread Best Practices:
It is best to set the Thread name Thread. name and Thread group ThreadGroup for convenient management. When a problem occurs, print the thread stack (jstack-pid) at a glance to see which thread has the problem and what the thread is doing.

How to obtain exceptions in a thread

Runnable

Similar to Thread

Callable

Future mode: One of the concurrency modes, which can be in two forms: no blocking or blocking, isDone and get. The Future object is used to store the return value and status of the thread.

9 Yin Zhenjing: advanced multi-thread control

All of the above are internal examples, followed by tools commonly used in actual projects. Java1.5 provides a very efficient and practical multi-threaded package:Java. util. concurrentProvides a large number of advanced tools to help developers write efficient, easy-to-maintain, and well-structured Java multi-threaded programs.

1. ThreadLocal class

Usage: stores independent variables of a thread. For a Thread class (inherited from Thread)
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. It is often used for user logon control, such as recording session information.

Implementation: Each Thread holds a variable of the TreadLocalMap type (this class is a lightweight Map with the same functions as map. The difference is that the bucket stores the entry instead of the entry linked list. The function is still a map .) Use this as the key and use the target as the value.
The main methods are get () and set (T a). After set, maintain a threadLocal-> a in the map. When get, a is returned. ThreadLocal is a special container.

2. Atomic classes (AtomicInteger, AtomicBoolean ......)

If you use atomic wrapper class such as atomicInteger, or use your own atomic operation, it is equivalent to synchronized.

This method can be used to implement optimistic locks. Consider the following scenario: a pays 10 yuan for B, a deducts 10 yuan, and B needs 10 yuan. At this time, c gives b2 yuan, but the code for adding 10 yuan to B is about:

AtomicReference
For AtomicReference, the object may be lost, that is, oldObject = current, but oldObject. getPropertyA! = Current. getPropertyA.
At this time, AtomicStampedReference came in handy. This is also a common idea, that is, to add the version number.

3. Lock class

Lock: in the java. util. concurrent package. There are three implementations:

  • ReentrantLock
  • ReentrantReadWriteLock. ReadLock
  • ReentrantReadWriteLock. WriteLock

The main purpose is to be like synchronized. Both of them are technologies generated to solve synchronization problems and deal with resource disputes. Functions are similar, but there are some differences.

The differences are as follows:

ReentrantLock    
The significance of reentrant is that the thread holding the lock can continue to hold the lock, and the lock will be released only after the number of equal requests are released.
The usage is as follows:

1. First create an instance

2. Lock

The difference is that the latter can be interrupted. When thread a is locked, thread B is blocked. If it is lockInterruptibly, the thread B is called. after interrupt (), the B-thread exits and blocks the block. Then, it gives up competition for resources and enters the catch Block. (If the latter is used, throw interruptable exception or catch is required)

3. Release the lock

Required! What is necessary? Put it in finally. To prevent exceptions from jumping out of normal processes and causing disasters. Here we add a small point of knowledge. finally is trustworthy: after testing, even if an OutofMemoryError occurs, the statement execution in the finally block can be ensured.

ReentrantReadWriteLock

Reentrant write lock (an implementation of read/write lock)

Both have the lock and unlock methods. Write and read are mutually exclusive; read is not mutually exclusive. Efficient thread-safe code for concurrent reading

4. Containers

Here we will discuss two common examples:

  • BlockingQueue
  • ConcurrentHashMap

BlockingQueue
Blocking the queue. This class is an important class in the java. util. concurrent package. We can learn from the Queue that this queue is a one-way Queue. You can add elements in the queue header and delete or retrieve elements at the end of the Queue. Similar to a channel, it is especially suitable for some application scenarios with a first-in-first-out policy. The common queue interface mainly implements PriorityQueue (priority queue), which can be studied if you are interested.

BlockingQueue adds the multi-thread collaboration function based on the queue:

In addition to the traditional queue function (two columns on the left of the table), it also provides the put and take blocking interfaces, the offer and poll blocking interfaces with the timeout function. Put will be blocked when the queue is full, until it is awakened when there is space; take will be blocked when the queue is empty, and will not be awakened until something is available. It is especially useful for producer-consumer models.

Common blocking queues include:

  • ArrayListBlockingQueue
  • LinkedListBlockingQueue
  • DelayQueue
  • SynchronousQueue

ConcurrentHashMap
Efficient thread-safe hash map. Compare hashTable, concurrentHashMap, and HashMap

5. Management

The management class concept is generic and used to manage threads. It is not multi-threaded, but provides some mechanisms to use the above tools for encapsulation.
It is worth mentioning the management class: ThreadPoolExecutor and ThreadMXBean, system-level management class under the JMX framework.
ThreadPoolExecutor
If you do not understand this class, you should understand the previously mentioned ExecutorService. It is very convenient to open your own thread pool:

This class is implemented internally through ThreadPoolExecutor. mastering this class helps to understand the management of thread pools. In essence, they are all implementation versions of the ThreadPoolExecutor class. See javadoc:

Translation:
CorePoolSize: The initial and minimum values of threads in the pool. This number of threads is maintained even if they are idle.
MaximumPoolSize: Maximum thread value. The thread growth will never exceed this value.
KeepAliveTime: When the number of threads in the pool is higher than the corePoolSize, The Idle threads that have been idle will be recycled. Wait Status before recycling
Unit:
Time unit. You can use TimeUnit instances, such as TimeUnit. MILLISECONDS.
WorkQueue: The waiting place of the waiting task (Runnable). This parameter mainly affects the scheduling policy, such as fairness or not, whether or not starving is generated)
ThreadFactory: Thread factory class, which has a default implementation. If you need to customize it, you need to implement the ThreadFactory interface and pass it as a parameter.

Note: This class is very common, and the author's 80% multithreading problem depends on him.

I have a public account that will often share some Java-related things. If you like it, you can search for "Java headers" or "javatuanzhang.

Refer:

  • Multithreading in Java is enough for you to read this article.
  • Java multi-thread Learning (conclusion)
  • Java multi-thread dry goods series (1): Java multi-thread Basics

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.