Multi-thread interview questions (2020)

Multithreading
1. What is the difference between parallel and concurrent?
Parallel: Multiple tasks are executed on the same CPU core in turns (alternately) in subdivided time slices. Logically, those tasks are executed simultaneously.
Concurrency: Multiple processors or multi-core processors process multiple tasks simultaneously.
As shown below:
concurrent and parallel concurrent = two queues and a coffee machine. Parallel = two queues and two coffee machines.

2. The difference between threads and processes?
There is at least one process under one program, at least one thread under one process, and multiple threads under one process to increase the execution speed of the program.

3. What is a daemon thread?
A daemon thread is a special process running in the background. It is independent of the control terminal and periodically performs certain tasks or waits for certain events to occur. In Java, the garbage collection thread is a special daemon thread.

4. What are the ways to create threads?
There are three ways to create threads: inherit the Thread rerun method; implement the Runnable interface; implement the Callable interface.

5. What is the difference between runnable and callable?
runnable has no return value, callable can get a return value, and callable can be seen as a supplement to runnable.

6. What are the state of the thread?
The state of the thread: NEW has not been started
RUNNABLE is being executed BLOCKED blocked (synchronized lock or IO lock blocked) WAITING permanent wait state TIMED_WAITING wait for the specified time to be reawakened state TERMINATED execution completed

7. What is the difference between sleep () and wait ()?
Different classes: sleep () comes from Thread, wait () comes from Object. Release the lock: sleep () does not release the lock; wait () releases the lock. The usage is different: sleep () will automatically recover when the time is up; wait () can be directly awakened using notify () / notifyAll ().

8. What is the difference between notify () and notifyAll ()?
notifyAll () will wake up all threads, notify () wakes up a thread.
After notifyAll () is called, all threads will be moved from the waiting pool to the lock pool, and then participate in the competition of the lock. If the competition is successful, it will continue to execute. If it is not successful, it will stay in the lock pool and wait for the lock to be released to participate in the competition again.
Notify () will only wake up one thread, which thread is specifically controlled by the virtual machine.

9. What is the difference between thread's run () and start ()?
The start () method is used to start the thread, and the run () method is used to execute the thread's runtime code. run () can be called repeatedly, but start () can only be called once.

10. What are the several ways to create a thread pool?
There are seven ways to create a thread pool, the core is the last one:
newSingleThreadExecutor (): It is characterized by the number of worker threads is limited to 1, operating a *** work queue, so it guarantees that all tasks are Being executed sequentially, at most one task will be active, and the user is not allowed to change the thread pool instance, so it can avoid changing the number of threads;
newCachedThreadPool (): It is a thread pool used to process a large number of short-time work tasks , Has several distinctive features: it will try to cache threads and reuse, when no cache thread is available, it will create a new worker thread; if the thread is idle for more than 60 seconds, it will be terminated and moved out of the cache; when idle for a long time This kind of thread pool will not consume any resources. SynchronousQueue is used internally as a work queue; newFixedThreadPool (int nThreads): reuse a specified number of threads (nThreads), behind which is the use of *** work queue, at any time at most nThreads worker threads are active. This means that if the number of tasks exceeds the number of active queue, the wait in the work queue of idle threads appear; if there are worker threads exit, there will be a new worker thread is created to make up the specified number nThreads;
newSingleThreadScheduledExecutor (): Create a single-threaded pool and return to ScheduledExecutorService for scheduled or periodic work scheduling;
newScheduledThreadPool (int corePoolSize): Similar to newSingleThreadScheduledExecutor (), it creates a ScheduledExecutorService, which can perform scheduled or periodic work scheduling. The difference is whether it is a single worker thread or multiple worker threads. Ignore the thread pool, Java 8 only added this creation method, it will build ForkJoinPool internally, use the Work-Stealing algorithm to process tasks in parallel, and do not guarantee the processing order;
ThreadPoolExecutor (): is the most original thread pool creation, above 1- 3 The creation methods are all encapsulation of ThreadPoolExecutor.

11. What are the states of the thread pool?
RUNNING: This is the most normal state, accepting new tasks and processing tasks in the waiting queue.
SHUTDOWN: Do not accept new task submissions, but will continue to process tasks in the waiting queue.
STOP: Do not accept new task submissions, no longer process tasks in the waiting queue, and interrupt the thread that is executing the task.
TIDYING: All tasks are destroyed, workCount is 0, and the state of the thread pool is changed to TIDYING state, the hook method terminated () is executed.
TERMINATED: After the terminated () method ends, the state of the thread pool becomes this. What is the difference between submit () and execute () methods in the thread pool? execute (): Can only execute Runnable tasks.
submit (): Can execute Runnable and Callable tasks.
Callable tasks can get the execution return value, while Runnable execution has no return value.
12. How to ensure the safety of multi-thread operation in Java programs?
Method 1: Use security classes, such as the classes under Java. Util. Concurrent.
Method two: use automatic lock synchronized.
Method 3: Use manual lock. The Java code for manual lock is as follows: Lock lock = new ReentrantLock (); lock. Lock (); try {System. Out. Println (“Acquire lock”);} catch (Exception e) {// TODO: handle exception} finally {System. Out. Println ("Release lock"); lock. Unlock ();
}

  1. What is the principle of synchronized lock escalation in multithreading?
    The principle of synchronized lock upgrade: There is a threadid field in the object header of the lock object. The threadid is empty when it is accessed for the first time. The jvm lets it hold the biased lock and sets the threadid to its threadid. When it enters again, it will First determine whether the threadid is consistent with its thread id. If it is consistent, you can use this object directly. If it is not consistent, the upgrade bias lock is a lightweight lock. The lock is obtained through a certain number of spin cycles. After a certain number of executions, if it is not normal After obtaining the object to be used, the lock will be upgraded from a lightweight to a heavyweight lock. This process constitutes the upgrade of a synchronized lock. The purpose of the lock upgrade: lock upgrade is to reduce the performance consumption caused by the lock. The optimized implementation of synchronized after Java 6 uses a biased lock upgrade to a lightweight lock and then to a heavyweight lock, thereby reducing the performance cost of locks.
    14. What is a deadlock?
    When thread A holds exclusive lock a, and attempts to acquire exclusive lock b, while thread B holds exclusive lock b, and attempts to acquire exclusive lock a, it will happen that two threads AB need each other to hold each other. The blocking phenomenon that occurs, we call it deadlock.
    15. How to prevent deadlock?
    Try to use tryLock (long timeout, TimeUnit unit) method (ReentrantLock, ReentrantReadWriteLock), set the timeout period, timeout can exit to prevent deadlock. Try to use Java. Util. Concurrent concurrent class instead of your own handwriting lock. Try to reduce the granularity of the lock, try not to use the same lock for several functions. Minimize the number of synchronized code blocks.
    16. What is ThreadLocal? What are the usage scenarios?
    ThreadLocal provides independent copies of variables for each thread that uses the variable, so each thread can independently change its own copy without affecting the copies corresponding to other threads. The classic usage scenarios of ThreadLocal are database connection and session management.
    17. What is the underlying implementation principle of synchronized?
    Synchronized is implemented by a pair of monitorenter / monitorexit instructions, and the monitor object is the basic unit of synchronization. Prior to Java 6, the implementation of the monitor completely relied on the mutex inside the operating system. Because the user mode to the kernel mode needs to be switched, the synchronization operation is a heavyweight operation with no difference, and the performance is also very low. But when Java 6, Java virtual machine conducted a large
    knife wide ax improvement, provides three different monitor implementation, which is often said that three different locks: Lock biased (Biased Locking), lightweight Grade locks and heavyweight locks have greatly improved their performance.
    18. What is the difference between synchronized and volatile?
    volatile is a variable modifier; synchronized is a modified class, method, and code segment. Volatile can only achieve the modified visibility of variables, and cannot guarantee atomicity; while synchronized can guarantee the modified visibility and atomicity of variables. volatile does not cause thread blocking; synchronized may cause thread blocking.
    19. What is the difference between synchronized and Lock?
    synchronized can lock classes, methods, and code blocks; lock can only lock code blocks. Synchronized does not need to manually acquire and release locks. It is simple to use. If an exception occurs, it will automatically release the lock and will not cause a deadlock; while locks need to add and release locks by themselves. lock. Through Lock, you can know whether you have successfully obtained the lock, but synchronized can't do it. 20. What is the difference between synchronized and ReentrantLock?
    The early implementation of synchronized is relatively inefficient. Compared with ReentrantLock, the performance of most scenarios is quite different, but in Java 6 synchronized synchronization has been improved a lot. The main differences are as follows: ReentrantLock is more flexible to use, but must cooperate with the action of releasing the lock; ReentrantLock must manually acquire and release the lock, and synchronized does not require manual release and unlocking of the lock; ReentrantLock is only applicable to code block locks, and synchronized can be used to modify Methods, code blocks, etc. Variables marked with volatile are not optimized by the compiler; variables marked with synchronized can be optimized by the compiler.
  2. Tell me about the principle of atomic?
    atomic mainly uses CAS (Compare And Wwap) and volatile and native methods to ensure atomic operations, thereby avoiding the high overhead of synchronized and greatly improving the execution efficiency.

Guess you like

Origin blog.51cto.com/14760318/2486660