[Interview] Java Concurrency (1)

0. Question outline

1. Concepts and tools

1、进程和线程
 - 追问1:Java线程有几种状态?

2、什么是线程安全,怎么保证多线程线程安全?(*43、线程的局部变量
 - 追问1:为什么安全?
 - 追问2:如何跨越方法边界呢?

4、什么情况下Java程序会产生死锁?(*2)如何定位、修复?(*2)【第18讲】(死锁处理办法)
 - 追问1:Java调试命令。看线程运行状态用什么?看堆栈信息用什么?

5、如何终止一个正在运行的线程?
 - 追问1:如何优雅终止线程池?

1. Concepts and tools

1. Processes and threads

A process is the smallest resource allocation unit, and a thread is the smallest running unit . Threads share resources such as the memory space of the same process . There can be one or more threads under a process, and each thread has an independent set of registers and stacks, which ensures that the thread control flow is relatively independent.
1

补充:
1、协程是为了避免线程IO阻塞,能去做其他事情,因此把程序逻辑封装在叫协程的抽象里。
Follow-up 1: How many states does a Java thread have?

2

Follow-up 2: In which area the thread is waiting, talk about it in detail

...... (not clear for the time being)

2. What is thread safety and how to ensure multi-threaded thread safety? (*4)

Thread safety: different threads access the same resource without errors or unpredictable results.

Guarantee method: synchronized, Volatile, concurrent tools, Reentrant Locks, etc.

supplement:

the way content specific
Concurrent collection java.util.concurrent 包 ConcurrentHashMap()
Atomic object AtomicInteger、AtomicLong、AtomicXXX……
Synchronization method synchronized modified method/statement synchronized keyword
Volatile Solve the problem of visibility between threads and ensure that the JVM reads/writes the main memory instead of the CPU cache. Volatile modified variable
Reentrant Locks Improved Lock implementation ReentrantLock
Read/write lock It can be realized that if there is no thread to write, there can be many threads to read the resource, otherwise it will prevent other threads from taking it. ReadWriteLock
Stateless realization
Immutable implementation
Thread local variables Fields are localized and will not be shared between threads
Synchronous collection Collections.synchronizedCollection()
External lock

……

3. Thread local variables

Local variables: variables inside the method.

//生成斐波那契数列
public int[] fibonacci(int n){
    
    
    //存放结果的数组
    int[] result = new int[n];
    //数组的第1项和第2项为1
    result[0] = result[1] = 1;
    //计算第3项到第n项
    for(int i = 2; i < n; i++){
    
    
        result[i] = result[i-2] + result[i-1];
    }
    return result;  // 调用result生成斐波那契数列,result是安全的
}

No data competition is involved, and it is thread-safe.

Follow-up 1: Why is it safe?

Local variables are stored in the call stack. The stack frame is created when the method is called and destroyed when it returns.
4
Each thread has its own independent call stack, so there is no concurrency problem.
5

Follow-up 2: How to cross the method boundary?

The variable must be created in the heap.

4. Under what circumstances will a Java program deadlock? (*2) How to locate and repair? (*2) [Lecture 18] (Deadlock handling method)

A deadlock is a specific program state. Between entities, due to circular dependence, they are always waiting for each other, and no individual can move on. Deadlock not only occurs between threads, but also between processes with exclusive resources. Generally speaking, we mostly focus on deadlocks in multi-threaded scenarios, which means that two or more threads are permanently blocked because they hold each other's locks.

You can use the following sample diagram to understand the basic deadlock problem:
9

The most common way to locate a deadlock is to use tools such as jstack to obtain the thread stack, and then locate the dependencies between each other, and then find the deadlock. If it is a more obvious deadlock, often jstack etc. can be directly located, similar to JConsole, it can even perform limited deadlock detection on the graphical interface.

If a deadlock occurs while the program is running, it cannot be solved online in most cases. You can only restart and correct the problem of the program itself. Therefore, it is often important to review each other during the code development phase, or use tools for preventive investigation.

Follow-up 1: Java debugging commands. What is the thread running status? What is used to see the stack information?

……

5. How to terminate a running thread?

stop(): Use a sword to seal the throat, and the terminated thread has no chance to take care of the funeral. It is not recommended to use it.
interrupt(): You can convert the sleeping thread to the RUNNAVBLE state, set the interrupt bit, and then determine whether to abort.
...

Follow-up 1: How to terminate the thread pool gracefully?

Methods: shutdown() and shutdownNow()
shutdown(): conservative, after execution, no new tasks are received, but it will wait for the execution of the executing and blocking tasks to complete before finally shutting down.
shutdownNow(): Radical, rejecting new tasks, and forcibly stopping tasks in execution and blocking queues at the same time, graceful termination requires correct processing of thread interruptions.

Two, reference

1. Programmers must be clear about processes and threads
2. Processes, threads, and coroutines in the practice of Kotlin coroutines
3. Are processes, threads, and coroutines still silly and confused? P7 big guys explain in vernacular, you can understand directly in seconds.
4, 09 | Java Thread (Part 1): The life cycle of Java Thread
5. What is thread safety? How to achieve?
6. [High Concurrency] The interviewer asked me: Why are local variables thread-safe?
7. 35 | Two-stage termination mode: How to terminate a thread gracefully?

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/112613534