Interview must ask knowledge points-multi-threaded, 50 interview questions summary (recommended collection)

Golden nine silver ten, entering the peak of job hunting, the latest and most comprehensive multi-threaded concurrent interview 50 questions and answer summary, I hope it will be helpful to students who want to enter BAT, because of the long space, it is recommended to read carefully after collection~

Due to limited space, only a part of it is shown here, and the rest of the knowledge points have been organized into documents. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN

1. Three elements of concurrent programming?

1) Atomicity

Atomicity refers to one or more operations, either all are executed and not interrupted by other operations during execution, or all are not executed.

2) Visibility

Visibility means that when multiple threads manipulate a shared variable, after one thread modifies the variable, other threads can immediately see the result of the modification.

3) Orderliness

Orderliness, that is, the order of execution of the program is executed in the order of the code.

2. What are the ways to achieve visibility?

Synchronized or Lock: Ensure that only one thread acquires the lock to execute code at the same time, and flushes the latest value to the main memory before the lock is released to achieve visibility.

3. The value of multithreading?

1) Take advantage of multi-core CPU

Multi-threading can really give play to the advantages of multi-core CPUs, and achieve the purpose of making full use of the CPU, using multi-threading to complete several things at the same time without interfering with each other.

2) Prevent blocking

From the perspective of program efficiency, a single-core CPU will not only not give play to the advantages of multi-threading, but will also cause thread context switching due to running multiple threads on a single-core CPU, which will reduce the overall efficiency of the program. But for single-core CPU, we still have to use multi-threading, just to prevent blocking. Imagine that if a single-core CPU uses a single thread, then as long as the thread is blocked, for example, reading a certain data remotely, the peer has not returned and the timeout period is not set, then your entire program will be before the data returns. Stopped running. Multithreading can prevent this problem. Multiple threads run at the same time, even if one thread's code execution is blocked for reading data, it will not affect the execution of other tasks.

3) Easy to model

This is another advantage that is not so obvious. Suppose there is a big task A, single-threaded programming, then there are a lot of considerations, and it is troublesome to build the entire program model. However, if we decompose this large task A into several small tasks, task B, task C, and task D, build the program model separately, and run these tasks separately through multithreading, it is much simpler.

4. What are the ways to create threads?

1) Inherit the Thread class to create a thread class

2) Create thread class through Runnable interface

3) Create thread through Callable and Future

4) Created by thread pool

5. Comparison of the three ways of creating threads?

1) Create multiple threads by implementing Runnable and Callable interfaces.

Advantages :

The thread class only implements the Runnable interface or the Callable interface, and can also inherit from other classes.

In this way, multiple threads can share the same target object, so it is very suitable for multiple same threads to process the same resource, so that CPU, code and data can be separated to form a clear model and better reflect The idea of ​​object-oriented.

Disadvantages :

Programming is slightly more complicated. If you want to access the current thread, you must use the Thread.currentThread() method.

2) Create multithreading by inheriting the Thread class

Excellent potential:

It is easy to write. If you need to access the current thread, you do not need to use the Thread.currentThread() method, and you can use this directly to get the current thread.

Disadvantages :

The thread class has inherited the Thread class, so it can no longer inherit from other parent classes.

3) The difference between Runnable and Callable

Callable provides (override) method is call(), Runnable provides (override) method is run().
Callable tasks can return values ​​after execution, but Runnable tasks cannot return values.
The Call method can throw exceptions, but the run method cannot.
Running the Callable task can get a Future object, which represents the result of asynchronous calculation. It provides a way to check whether the calculation is complete, wait for the completion of the calculation, and retrieve the result of the calculation. Through the Future object, you can understand the execution of the task, cancel the execution of the task, and get the execution result.

6. Java threads have five basic states

1) New state (New): When the thread object pair is created, it enters the new state, such as: Thread t = new MyThread();

2) Ready state (Runnable): When the start() method (t.start();) of the thread object is called, the thread enters the ready state. The thread in the ready state only means that the thread is ready and waiting for the CPU to schedule execution at any time, not that the thread will execute immediately after executing t.start();

3) Running state (Running): When the CPU starts to schedule a thread in the ready state, then the thread can actually execute, that is, it enters the running state. Note: The ready
state is the only entry to the running state, that is, if a thread wants to enter the running state for execution, it must first be in the ready state;

4) Blocked: For some reason, the thread in the running state temporarily gives up the right to use the CPU and stops execution. At this time, it enters the blocked state. Until it enters the ready state, it has the opportunity to be called by the CPU again To enter the running state.

According to the different causes of blocking, the blocking state can be divided into three types:

a. Waiting for blocking: the thread in the running state executes the wait() method to make the thread enter the waiting blocking state;

b. Synchronous blocking-the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads), it will enter the synchronized blocking state;

c. Other blocking-By calling the thread's sleep() or join() or issuing an I/O request, the thread will enter the blocking state. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread turns to the ready state again.

5) Dead state (Dead): The thread finishes its execution or exits the run() method due to an exception, and the thread ends its life cycle.

7. What is a thread pool? What are the ways to create it?

The thread pool is to create several threads in advance. If there are tasks to be processed, the threads in the thread pool will process the tasks. After processing, the threads will not be destroyed, but will wait for the next task. Since the creation and destruction of threads consume system resources, you can consider using thread pools to improve system performance when you want to create and destroy threads frequently.

Java provides an implementation of the java.util.concurrent.Executor interface for creating thread pools.

8. What are the advantages of thread pools?

1) Reuse existing threads to reduce the overhead of object creation and destruction.

2) It can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, and avoid excessive resource competition and blockage.

3) Provide functions such as timing execution, regular execution, single thread, and concurrent number control.

9. The difference between CyclicBarrier and CountDownLatch

1) CountDownLatch simply means that a thread waits until the other threads it is waiting for are executed and the countDown() method is called to notify, the current thread can continue to execute.

2) cyclicBarrier is that all threads wait until all threads are ready to enter the await() method, all threads start executing at the same time!

3) The counter of CountDownLatch can only be used once. The counter of CyclicBarrier can be reset using the reset() method. Therefore, CyclicBarrier can handle more complex business scenarios. For example, if an error occurs in the calculation, the counter can be reset and the threads can be executed again.

4) CyclicBarrier also provides other useful methods, such as getNumberWaiting method to get the number of threads blocked by CyclicBarrier. The isBroken method is used to know whether the blocked thread is interrupted. Return true if interrupted, otherwise return false.

10. The role of the volatile keyword

For visibility, Java provides the volatile keyword to ensure visibility.

When a shared variable is modified by volatile, it will ensure that the modified value will be updated to the main memory immediately. When other threads need to read it, it will go to the memory to read the new value.

From a practical point of view, an important role of volatile is to combine with CAS to ensure atomicity. For details, please refer to the classes in the java.util.concurrent.atomic package, such as AtomicInteger.

11. What is CAS

CAS is the abbreviation of compare and swap, which is what we call compare exchange.

Cas is a lock-based operation, and it is an optimistic lock. Locks are divided into optimistic locks and pessimistic locks in java. Pessimistic lock is to lock the resource, and the next thread can only access it after a thread that previously acquired the lock releases the lock. Optimistic locking adopts a broad attitude, dealing with resources in some way without locking, such as obtaining data by adding version to the record, performance is greatly improved compared to pessimistic locking.

CAS operation consists of three operands-memory location (V), expected original value (A) and new value (B). If the value in the memory address is the same as the value of A, then the value in the memory is updated to B. CAS obtains data through an infinite loop. If in the first round of the loop, the value in the address obtained by the a thread is modified by the b thread, then the a thread needs to spin, and it may have a chance to execute in the next loop.

Most of the classes under the java.util.concurrent.atomic package are implemented using CAS operations (AtomicInteger, AtomicBoolean, AtomicLong).

12. The CAS problem

1) CAS easily causes ABA problems

A thread a changed the value to b, and then changed to a. At this time, CAS thinks that there is no change, but it has changed. The solution to this problem can be identified by the version number, and version is incremented by 1 for each operation. . In java5, AtomicStampedReference has been provided to solve the problem.

2) The atomicity of code blocks cannot be guaranteed

The CAS mechanism guarantees the atomic operation of a variable, but cannot guarantee the atomicity of the entire code block. For example, if you need to ensure that three variables are updated atomically together, you have to use synchronized.

3) CAS causes an increase in CPU utilization

As mentioned before, CAS is a cyclic judgment process. If the thread has not obtained the status, the cpu resources will always be occupied.

13. What is Future?

In concurrent programming, we often use the non-blocking model. In the previous three implementations of multithreading, whether it is inheriting the thread class or implementing the runnable interface, there is no guarantee that the previous execution results will be obtained. By implementing the Callback interface and using Future, you can receive the results of multi-threaded execution.

Future represents the result of an asynchronous task that may not be completed. For this result, a Callback can be added to perform the corresponding operation after the task execution succeeds or fails.

14. What is AQS

AQS is the abbreviation of AbustactQueuedSynchronizer. It is a Java-improved low-level synchronization tool class. It uses an int type variable to represent the synchronization state and provides a series of CAS operations to manage this synchronization state.

AQS is a framework for building locks and synchronizers. AQS can be used to easily and efficiently construct a large number of synchronizers for a wide range of applications, such as ReentrantLock, Semaphore, and others such as ReentrantReadWriteLock, SynchronousQueue, FutureTask, etc. It is based on AQS.

15. AQS supports two synchronization methods:

1) Exclusive ceremony

2) Shared

This makes it easy for users to implement different types of synchronization components, such as exclusive types such as ReentrantLock, shared types such as Semaphore, CountDownLatch, and combined types such as ReentrantReadWriteLock. In short, AQS provides the bottom support for use, how to assemble and realize, users can play freely.

At last

Hope this article is helpful to everyone!

I have also compiled a complete set of video tutorials for architects and systematic materials on java, including java core knowledge points, interview topics, and the latest 20 years of Internet real questions and e-books. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN
Insert picture description here

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/108719612