Arrangement of multi-threaded interview questions (27 questions with answers)

  1. Talk about the difference between processes and threads.
    In short, a process is the basic unit of program operation and resource allocation.
    A program has at least one process, and a process has at least one thread. The
    process has an independent memory unit during execution, and Multiple threads share memory resources, reducing the number of switching, and thus higher efficiency.
    A thread is an entity of a process, the basic unit of CPU scheduling and allocation, and a basic unit that is smaller than a program and can run independently. Multiple threads in the same process can execute concurrently.

  2. Do you understand daemon threads? What is the difference between it and a non-daemon thread?
    After the program runs, the JVM will wait for the non-daemon thread to complete and then shut down, but the JVM will not wait for the daemon thread. The most classic example of a daemon thread is the GC thread.

  3. What is multi-threaded context switching?
    Multi-threaded context switching refers to the process in which CPU control is switched from a thread that is already in progress to another thread that is ready and waiting to obtain CPU execution rights.

  4. What is the difference between Runnable and Thread to create threads?
    It may be better to implement the Runnable interface.
    There are two reasons:
    (1) Java does not support multiple inheritance, so extending the Thread class means that this subclass cannot extend other classes, and the class that implements the Runnable interface may extend another class
    (2) The class may only be executable. , So the overhead of inheriting the entire Thread class is too large.

  5. The difference between Runnable and Callable The
    return value of the run() method in the Runnable interface is void, what it does is purely to execute the code in the run() method;
    the call() method in the Callable interface has a return value , Is a generic type, and can be used in conjunction with Future and FutureTask to obtain the result of asynchronous execution.
    This is actually a very useful feature, because multi-threading is more difficult and more complicated than single-threaded. An important reason is that multi-threading is full of unknowns. Has a thread executed? How long has a thread been executed? Has the data we expect when a thread executes has been assigned? It is impossible to know that all we can do is wait for the completion of this multi-threaded task. However, Callable+Future/FutureTask can easily obtain the results of multi-threaded operation, and can cancel the task of the thread when the waiting time is too long to obtain the required data.

  6. Conditions for deadlock
    (1) Mutually exclusive conditions: A resource can only be used by one process at a time
    (2) Request and hold conditions: When a process blocks in response to a request for resources, it keeps the acquired resources.
    (3) Non-deprivation conditions: the resources already acquired by the process cannot be deprived forcibly before they are used up.
    (4) Cyclic waiting condition: A cyclic waiting resource relationship is formed between several processes.

  7. Why wait() method and notify()/notifyAll method should be called in synchronized block
    This is mandatory by JDK, wait() method and notify()/notifyAll() method must obtain the lock of the object before calling.

  8. Why wait, notify, and notifyAll are not placed in the Thread class.
    An obvious reason is that the locks provided by JAVA are object-level rather than thread-level. Each object has a lock, which is obtained through a thread. If the thread needs to wait for some locks then it makes sense to call the wait() method of the object. If the wait() method is defined in the Thread class, it is not obvious which lock the thread is waiting for.
    Simply put, since wait, notify, and notifyAll are lock-level operations, they are defined in the Object class because the lock belongs to the object.

  9. How to wake up a blocked thread
    If the thread is blocked by calling wait(), sleep() or join(), you can interrupt the thread and wake it up by throwing InterruptedException;
    if the thread encounters IO blocking, nothing can be done , Because IO is implemented by the operating system, there is no way for Java code to directly touch the operating system.

  10. What is FutureTask?
    In fact, as mentioned earlier, FutureTask represents an asynchronous operation task, and a specific implementation class of Callable can be passed into FutureTask, which can wait for the result of this asynchronous operation task to determine whether it has been completed, cancel the task, etc. . Of course, because FutureTask is also an implementation class of the Runnable interface, FutureTask can also be placed in the thread pool.

  11. What if a thread has a runtime exception?
    If the exception is not caught, the thread stops executing.
    Another important point is: if this thread holds the monitor of an object, then the object monitor will be released immediately.

  12. What kind of locks are there in Java?
    (1) Spin lock: Spin lock is enabled by default after JDK1.6. Based on previous observations, the locked state of shared data will only last for a short time. Suspending and resuming threads for this short period of time is a bit wasteful, so here is a process to let the thread that requests the lock later. Wait a while, but don't give up the execution time of the processor, and see if the thread holding the lock can be released quickly. In order to let the thread wait, it is necessary to let the thread perform a busy loop, which is a spin operation. After jdk6, an adaptive spin lock was introduced, that is, the waiting event is no longer fixed, but is determined by the last optional time on the same lock and the state of the lock owner.
    (2) Biased locks: A lock optimization introduced after JDK1. The purpose is to eliminate data synchronization primitives without contention. Further improve the running performance of the thread. A biased lock is an eccentric bias, which means that the lock will be biased to the thread that acquires him first. If the lock is not acquired by other threads during the subsequent execution process, the thread holding the biased lock will never need to proceed again. Synchronize. The biased lock can improve the performance of the program with synchronization but no competition, which means that it is not always beneficial to the running of the program. If most of the locks in the program are accessed by multiple different threads, then the biased mode is redundant Yes, on the premise of specific analysis of specific issues, you can consider whether to use biased locks.
    (3) Lightweight locks: In order to reduce the performance cost of acquiring and releasing locks, "biased locks" and "lightweight locks" are introduced. Therefore, there are four lock states in Java SE1.6: None Lock state, biased lock state, lightweight lock state and heavyweight lock state, it will gradually upgrade with competition. The lock can be upgraded but cannot be downgraded, which means that the partial lock can be upgraded to a lightweight lock and cannot be downgraded to a partial lock.

  13. How to share data between two threads
    is enough by sharing objects between threads, and then awakening and waiting through wait/notify/notifyAll, await/signal/signalAll, for example, blocking queue BlockingQueue is to share data between threads Designed.

  14. How to use wait() correctly? Use if or while?
    The wait() method should be called in a loop, because when the thread gets the CPU to start execution, other conditions may not be met, so it is better to loop to check whether the conditions are met before processing. The following is a standard code that uses wait and notify methods:
    synchronized(obj){ while(condition does not hold) obj.wait(); //. . . . . . (Omitted here)


  15. What is the thread local variable ThreadLocal?
    Thread local variables are variables that are confined to the thread and belong to the thread itself and are not shared among multiple threads. Java provides the ThreadLocal class to support thread local variables, which is a way to achieve thread safety. But be careful when using thread-local variables in a managed environment (such as a web server). In this case, the life cycle of a worker thread is longer than the life cycle of any application variable. Once any thread-local variable does not have a yes or no after the work is completed, there is a risk of memory leaks in Java applications.

  16. What is the role of ThreadLocal?
    Simply put, ThreadLocal is a way of changing space for time. A ThreadLocal.ThreadLocalMap is maintained in each Thread to isolate data. If data is not shared, there will naturally be no thread safety issues.

  17. What is the role of the producer consumer model?
    (1) Provide a balance between the production capacity of the producer and the consumption capacity of the consumer to improve the operating efficiency of the entire system. This is the most important role of the producer model.
    (2) Decoupling, which is an incidental role of the producer-consumer model. Decoupling means that there are fewer connections between producers and consumers. The fewer connections, the more they can develop independently without mutual constraints.

  18. What happens if the thread pool queue is full when you submit a task?
    If you use LinkedBlockingQueue, which is an unbounded queue, it does not matter. Continue to add tasks to the blocking queue to wait for execution, because LinkedBlockingQueue can be regarded as an infinite queue, which can store tasks indefinitely;
    if you use a bounded queue, for example In the case of ArrayBlockingQueue, the task will be added to the ArrayBlockingQueue first. When the ArrayBlockingQueue is full, the rejection policy RejectedExecutionHandler will be used to process the full tasks. The default is AbortPolicy.

  19. Why use thread pool?
    Avoid frequent creation and destruction of threads, and achieve the reuse of thread objects.
    In addition, the use of thread pools can also flexibly control the number of concurrency according to the project.

  20. What is the thread scheduling algorithm used in Java?
    Preemptive.
    After a thread runs out of CPU, the operating system will calculate a total priority based on thread priority, thread starvation and other data and allocate the next time slice to a thread for execution.

  21. What is the function of Thread.sleep(0)?
    Because Java uses a preemptive thread scheduling algorithm, there may be a situation where a thread often obtains control of the CPU, in order to allow some threads with lower priority to also obtain CPU control, you can use Thread.sleep(0) to manually trigger an operation of the operating system to allocate time slices, which is also an operation to balance CPU control.

  22. What is CAS
    CAS, the full name is Compare and Swap, that is, compare-replace.
    Suppose there are three operands: the memory value V, the old expected value A, and the value to be modified B. If and only if the expected value A and the memory value V are the same, the memory value will be modified to B and return true, otherwise what Do nothing and return false. Of course, CAS must cooperate with volatile variables, so as to ensure that the variable obtained each time is the latest value in the main memory, otherwise the old expected value A will always be a constant value A for a certain thread, as long as If a CAS operation fails, it will never succeed.

  23. What is optimistic lock and pessimistic lock
    Optimistic lock: Optimistic lock believes that competition does not always occur, so he does not need to hold the lock. The two actions of comparison-replacement are used as an atomic operation to try to modify the variables in memory. If it fails It means that there is a conflict, then there should be corresponding retry logic.

Pessimistic lock: Pessimistic lock believes that competition will always occur, so every time a resource is operated, it will hold an exclusive lock, just like synchronized, no matter what the situation is, you can operate the resource directly when the lock is locked.

  1. What is the concurrency of ConcurrentHashMap?
    The concurrency of ConcurrentHashMap is the size of the segment. The default is 16, which means that up to 16 threads can operate ConcurrentHashMap at the same time. This is also the biggest advantage of ConcurrentHashMap to Hashtable. In any case, Hashtable can have two threads to obtain Hashtable at the same time. Data?

  2. The working principle of
    ConcurrentHashMap ConcurrentHashMap is different in JDK1.6 and JDK1.8.
    JDK1.6: ConcurrentHashMap is thread-safe, but compared with Hashtable, the way to achieve thread safety is different.
    Hashtable is a blocking type by locking the hash table structure. When a thread holds the lock, other threads must block and wait for it to release the lock.
    ConcurrentHashMap uses a separate lock method. It does not lock the entire hash table, but a partial lock, which means that when a thread occupies this partial lock, it does not affect other threads' access to other places in the hash table.
    Specific implementation: There is a Segment inside ConcurrentHashMap.
    In JDK1.8: ConcurrentHashMap no longer uses segment separation locks, but uses an optimistic lock CAS algorithm to achieve synchronization problems, but the bottom layer is still the realization of array + linked list -> red-black tree.

  3. Is the ++ operator thread safe in Java?
    Not a thread-safe operation. It involves multiple instructions, such as reading the value of a variable, increasing, and then storing it back to memory. This process may involve multiple threads crossing.

  4. What are the good practices for multi-threaded development?
    (1) Give the thread a name
    (2) Minimize the scope of synchronization
    (3) Use volatile first
    (4) Use higher-level concurrency tools as much as possible instead of wait and notify() to implement thread communication, such as BlockingQueue, Semeaphore
    (5) Prioritize the use of concurrent containers rather than synchronous containers
    (6) consider using thread pools

https://www.kancloud.cn/smartsean/android/1106143
Android interview document

Guess you like

Origin blog.csdn.net/ambitionLlll/article/details/115219364