This article takes you to understand what is concurrent programming

Don't talk nonsense, just deliver dry goods

1. What is livelock, starvation, no lock, deadlock?

Deadlock, livelock, and starvation are related to the running blocking problems of whether multithreading is active or not. If these three situations occur in the thread, that is, the thread is no longer active and can no longer execute normally.

Deadlock

Deadlock is the worst case in multithreading. Multiple threads occupy each other's resource locks and wait for each other to release the lock. At this time, if there is no external intervention, these threads will always deal with the blocked suspended animation state, forming Deadlock.

For example, classmate A grabbed classmate B's pen, classmate B grabbed classmate A's book, both of them occupy each other's things, and both are asking the other to return it to themselves first, so that the dispute continues to wait for the other to return And can't be resolved,

The teacher told them to return to each other after knowing the matter, so that they can solve it under the intervention of external forces. Of course, this is just an example. They can also solve it well without a teacher. The computer is not like a human. It has been blocked.

Livelock

Few people have heard or understood the concept of livelock, and it does exist in multithreading.

Livelock is just the opposite of deadlock. Deadlock is that everyone can't get resources and they occupy each other's resources, while livelock is that resources are obtained but they are released and not executed.

When mutual humility occurs in multiple threads, they actively release resources to other threads for use, so that this resource jumps between multiple threads without being executed, which is a livelock.

hunger

We know that there is thread priority in multi-threaded execution. High-priority threads can jump in and execute first. In this way, if high-priority threads have been preempting the resources of low-priority threads, the low-priority threads cannot be executed. It's hunger.

Of course, there is also a starvation situation. A thread keeps occupying a resource and other threads cannot be executed. The difference from deadlock is that starvation can still be executed for a period of time, such as the thread occupying resources. It is over and the resources are released.

no lock

No lock, that is, no resource is locked, that is, all threads can access and modify the same resource, but only one thread can modify successfully at the same time.

The typical feature of lock-free is that a modification operation is performed in a loop. The thread will continuously try to modify the shared resource. If there is no conflict, the modification succeeds and exits, otherwise it will continue the next loop attempt.

Therefore, if multiple threads modify the same value, one thread must be able to modify it successfully, and other threads that fail to modify will continue to retry until the modification is successful. In the previous article, I introduced the principle and application of JDK CAS, which is a lock-free implementation.

It can be seen that lock-free is a very good design. It will not cause the jumping problem of threads. Improper use of locks will definitely cause system performance problems. Although lock-free cannot fully replace locks, but lock-free is in some cases. The occasion is very efficient.

2. What is the difference between thread and process?

The main difference between processes and threads is that they are different operating system resource management methods. The process has an independent address space. After a process crashes, it will not affect other processes in the protected mode, and the threads are just different execution paths in a process.

Threads have their own stacks and local variables, but there is no separate address space between threads. The death of a thread means the death of the entire process. Therefore, a multi-process program is more robust than a multi-threaded program, but it costs more when switching between processes. The resources are larger and the efficiency is worse.

But for some concurrent operations that require simultaneous execution and share certain variables, only threads can be used, not processes.

3. How many ways does Java implement threads?

(1) Inherit the Thread class to implement multithreading

(2) Realize the Runnable interface to realize multithreading

(3) Use ExecutorService, Callable, Future to implement multithreading with returned results

(4) Create threads through the thread pool

4. What is the difference between start() and run() to start the thread?

Only when the start() method is called, will it show the characteristics of multithreading. The code in the run() method of different threads is executed alternately. If you just call the run() method, the code is executed synchronously, and you must wait for the code in the run() method of one thread to finish executing before another thread can execute the code in the run() method.

5. How to terminate a thread? How to terminate the thread gracefully?

stop terminates, not recommended.

6. What are the several states of the life cycle of a thread? How do they flow between them?

NEW: It undoubtedly means that the thread just created has not started yet.

RUNNABLE: Indicates that the thread has triggered the start() method call, the thread is officially started, and the thread is in a running state.

BLOCKED: Indicates that the thread is blocked and waiting to acquire a lock. For example, when a key area such as synchronized and lock is occupied by a critical area, once the lock is acquired, it will continue to run in the RUNNABLE state.

WAITING: Indicates that the thread is in an unlimited waiting state, waiting for a special event to wake up again. For example, a thread waiting through the wait() method waits for a notify() or notifyAll() method, and a waiting thread waiting through the join() method The target thread is awakened after running. Once the thread is awakened by a related event, the thread enters the RUNNABLE state and continues to run.

TIMED_WAITING: Indicates that the thread has entered a time-limited waiting, such as sleep(3000). After waiting for 3 seconds, the thread will resume running in the RUNNABLE state.

TERMINATED: Indicates that the thread is executed in a terminated state. It should be noted that once the thread is started through the start method, it can no longer return to the initial NEW state, nor can it return to the RUNNABLE state after the thread terminates.

7. What is the difference between wait() and sleep() methods in threads?

This question is often asked. Both the sleep method and the wait method can be used to give up the CPU for a certain amount of time. The difference is that if the thread holds the monitor of an object, the sleep method will not give up the monitor of this object, and the wait method will give up this. The monitor of the object.

8. What are the methods for multi-thread synchronization?

Synchronized keyword, Lock implementation, distributed lock, etc.

9. What is the use of multithreading?

  • Give full play to the advantages
    of multi-core CPUs. With the advancement of industry, current notebooks, desktops and even commercial application servers are at least dual-core. 4-core, 8-core or even 16-
    core are not uncommon. If it is a single-threaded program, So 50% was wasted on dual-core CPU, and 75% was wasted on 4-core CPU.

The so-called "multithreading" on a single-core CPU is false multithreading. The processor can only process a piece of logic at the same time, but the threads switch faster, and it looks like multiple threads are running "simultaneously".

Multi-threading on a multi-core CPU is the real multi-threading. It allows your multi-segment logic to work at the same time. Multi-threading can really give play to the advantages of the multi-core CPU and achieve the purpose of making full use of the CPU.

  • Preventing blocking
    From the perspective of program efficiency, a single-core CPU not only does not give play to the advantages of multithreading, but it will switch the thread context due to running multithreading on a single-core CPU, which reduces the overall efficiency of the program. But for single-core CPU, we still have to apply multi-threading, just to prevent blocking. Just think, if a single-core CPU
    using a single thread, so as long as this thread is blocked, say a data remotely read it, to end the delay in return
    before returning and no set time-out, then your entire program in return data back It 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.

  • 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. But if you divide this big task A into several small tasks, task B, task C, and task D, build program models separately, and run these tasks separately through multi-threading, it is much simpler.

10. How to communicate between multiple threads?

wait/notify

11. How does the thread get the returned result?

Implement the Callable interface.

12. What does the violatile keyword do?

A very important issue is that every Java programmer who learns and applies multithreading must master it. The prerequisite for understanding the role of the volatile keyword is to understand the Java memory model. The Java memory model is not discussed here. You can refer to point 31. The volatile keyword has two main functions:

  • Multithreading is mainly developed around the two characteristics of visibility and atomicity. The variable modified with the volatile keyword ensures its visibility between multiple threads, that is, every time a
    volatile variable is read , it must be the latest data.
  • The bottom-level execution of the code is not as simple as the high-level language we have seen-Java program, its execution is Java code -> bytecode -> execute the corresponding
    C/C++ code according to the bytecode -> C/C++ code It is compiled into assembly language -> interacts with hardware circuits. In reality, the JVM
    may reorder instructions in order to obtain better performance , and some unexpected problems may occur under multi-threading.

Using volatile will prohibit semantic reordering, of course, this also reduces code execution efficiency to a certain extent. From a practical point of view, an important role of volatile is to combine with CAS.

13. How to ensure that the three threads T1, T2 and T3 are newly created in order?

Use the join method.

14. How to control only 3 threads running at the same time?

用 Semaphore。

15. Why use thread pool?

We know that without thread pool, each thread has to create and run a thread through new Thread(xxRunnable).start(). If there are fewer threads, this will not be a problem.

In the real environment, multiple threads may be opened to achieve the best efficiency of the system and programs. When the number of threads reaches a certain number, the CPU and memory resources of the system will be exhausted, and it will also cause frequent GC collection and pauses because of creation and destruction each time A thread consumes system resources.

If threads are created for each task, this is undoubtedly a big performance bottleneck. Therefore, thread reuse in the thread pool greatly saves system resources. When a thread no longer has tasks to process for a period of time, it will be automatically destroyed instead of long-lived in memory.

Off topic

This is the end of this sharing about concurrent programming. Due to space limitations, only part of the content is released. Recently, it is the best time to find a job. If you want to get more concurrent programming related questions and interview questions from major vendors You can click here to get the information, code: qf The
following is a screenshot of some of the information (all the information has been integrated into a document, and the pdf is compressed and packaged).

Insert picture description here

Guess you like

Origin blog.csdn.net/S11035762/article/details/108665167