Interview questions summary (3) multi-threading

35. What is the difference between parallel and concurrent?

 

  • Parallel means that two or more events occur at the same time; while concurrency means that two or more events occur at the same time interval.

  • Parallelism is multiple events on different entities, and concurrency is multiple events on the same entity.

  • Multiple tasks are processed "simultaneously" on one processor, and multiple tasks are processed simultaneously on multiple processors. Such as hadoop distributed cluster.

 

Therefore, the goal of concurrent programming is to make full use of each core of the processor to achieve the highest processing performance.

 

36. The difference between threads and processes?

 

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 to reduce the number of switchovers, which is more efficient. A thread is an entity of a process, a basic unit of CPU scheduling and dispatch, and a basic unit that can run independently than a program. Multiple threads in the same process can execute concurrently.

 

37. What is a daemon thread?

 

A daemon thread (that is, a daemon thread) is a service thread, to be precise, it serves other threads.

 

38. What are the different ways to create threads?

 

①. Inherit Thread class to create thread class

 

  • Define a subclass of the Thread class and rewrite the run method of this class. The method body of the run method represents the task to be completed by the thread. Therefore, the run () method is called the executive body.

  • Create an instance of the Thread subclass, that is, create a thread object.

  • Call the thread object's start () method to start the thread.

 

②. Create thread class through Runnable interface

 

  • Define the implementation class of the runnable interface and rewrite the run () method of the interface. The method body of the run () method is also the thread execution body of the thread.

  • Create an instance of the Runnable implementation class, and use this instance as the Thread target to create a Thread object, which is the real thread object.

  • Call the thread object's start () method to start the thread.

 

③. Create thread through Callable and Future

 

  • Create an implementation class of the Callable interface and implement the call () method. The call () method will act as the thread execution body and have a return value.

  • Create an instance of the Callable implementation class and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the Callable object's call () method.

  • Use the FutureTask object as the target of the Thread object to create and start a new thread.

  • Call the get () method of the FutureTask object to obtain the return value after the execution of the child thread.

 

39. What is the difference between runnable and callable?

 

A bit deep question, also see the breadth of a Java programmer learning knowledge.

 

  • The return value of the run () method in the Runnable interface is void, and all it does is purely execute the code in the run () method;

  • The call () method in the Callable interface has a return value and is a generic type. It can be used with Future and FutureTask to obtain the results of asynchronous execution.

 

40. What are the state of the thread?

 

Threads usually have five states, created, ready, running, blocked, and dead.

 

  • Create a state. When the thread object is generated, the start method of the object is not called, which means that the thread is in the creation state.

  • Ready state. When the start method of the thread object is called, the thread enters the ready state, but the thread scheduler has not set the thread as the current thread at this time, and is in the ready state at this time. After the thread is running, it will be in a ready state after returning from waiting or sleeping.

  • Operating status. The thread scheduler sets the thread in the ready state as the current thread. At this time, the thread enters the running state and starts running the code in the run function.

  • Blocked state. When the thread is running, it is suspended, usually in order to wait for a certain time to occur (for example, a resource is ready) before continuing to run. Sleep, suspend, wait and other methods can cause threads to block.

  • State of death. If the run method of a thread is finished or the stop method is called, the thread will die. For the dead thread, you can no longer use the start method to make it ready   

 

41. What is the difference between sleep () and wait ()?

 

sleep (): The method is a static method of the thread class (Thread), which allows the calling thread to enter the sleep state and gives the execution opportunity to other threads. When the sleep time is over, the thread enters the ready state and competes with other threads for CPU execution time. Because sleep () is a static method, he cannot change the machine lock of the object. When the sleep () method is called in a synchronized block, although the thread goes to sleep, the machine lock of the object is not released, and other threads still cannot access this. Object.

 

wait (): wait () is a method of the Object class. When a thread executes the wait method, it enters a waiting pool related to the object, and at the same time releases the machine lock of the object so that other threads can access it and can pass notify, notifyAll methods to wake up waiting threads

 

42. What is the difference between notify () and notifyAll ()?

 

  • If the thread calls the object's wait () method, the thread will be in the object's waiting pool, and the threads in the waiting pool will not compete for the object's lock.

  • When a thread calls the notifyAll () method of the object (wake up all wait threads) or notify () method (only wake up a wait thread randomly), the awakened thread will enter the lock pool of the object. The thread will compete for the object lock. In other words, after calling notify, as long as a thread will enter the lock pool from the waiting pool, notifyAll will move all the threads in the object waiting pool to the lock pool and wait for lock competition.

  • The thread with high priority has a high probability of competing for the object lock. If a thread does not compete for the object lock, it will remain in the lock pool. Only when the thread calls the wait () method again will it return to the waiting pool in. The thread competing for the object lock continues to execute until the synchronized code block is executed, it will release the object lock, and then the threads in the lock pool will continue to compete for the object lock.

 

43. What is the difference between a thread's run () and start ()?

 

Each thread completes its operation through the method corresponding to a particular Thread object run (), which is called the thread body. Start a thread by calling the start () method of the Thread class.

 

The start () method starts a thread, which truly implements multithreading. At this time, there is no need to wait for the execution of the run method body code to complete, you can directly continue to execute the following code; this time the thread is in a ready state and is not running. Then call the method run () through this Thread class to complete its running state. The method run () is called the thread body, which contains the content of the thread to be executed. The Run method ends and the thread terminates. Then the CPU schedules other threads.

 

The run () method is in this thread, just a function in the thread, not multi-threaded. If you call run () directly, it is actually equivalent to calling a normal function. The direct standby run () method must wait for the run () method to complete before executing the following code, so there is only one execution path, and there is no thread at all. Feature, so use start () method instead of run () method in multi-thread execution.

 

44. What are the ways to create a thread pool?

 

①. newFixedThreadPool(int nThreads)

 

Create a fixed-length thread pool, create a thread every time a task is submitted, until the maximum number of thread pools is reached, then the thread size will no longer change, and when the thread ends with an unexpected error, the thread pool will supplement A new thread.

 

②. newCachedThreadPool()

 

Create a cacheable thread pool. If the size of the thread pool exceeds the processing requirements, idle threads will be automatically recovered. When the demand increases, new threads can be automatically added. There is no limit to the size of the thread pool.

 

③. newSingleThreadExecutor ()

 

This is a single-threaded Executor, which creates a single worker thread to perform a task. If this thread ends abnormally, a new one will be created to replace it; its feature is to ensure that the tasks are executed serially according to the order of the tasks in the queue.

 

④. newScheduledThreadPool(int corePoolSize)

 

Create a fixed-length thread pool, and perform tasks in a delayed or timed manner, similar to Timer.

 

45. What are the states of the thread pool?

 

The thread pool has 5 states: Running, ShutDown, Stop, Tidying, Terminated.

Thread pool state switching framework diagram:

 

46. ​​What is the difference between the submit () and execute () methods in the thread pool?

 

  • The received parameters are different

  • submit has a return value, but execute does not

  • submit to facilitate Exception handling

 

47. How to ensure the safety of multi-thread operation in java program?

 

Thread safety is reflected in three aspects:

 

  • Atomicity: providing mutually exclusive access, only one thread can operate on the data at the same time, (atomic, synchronized);

  • Visibility: The modification of main memory by one thread can be seen by other threads in time, (synchronized, volatile);

  • Orderliness: A thread observes the order of execution of instructions in other threads. Due to the reordering of instructions, the observation results are generally disordered (orders-before principle).

 

48. What is the principle of multi-thread lock upgrade?

 

In Java, there are 4 states of locks, from low to high levels: stateless locks, biased locks, lightweight locks, and heavyweight locks. These states will gradually upgrade with competition. The lock can be upgraded but not downgraded.

 

Graphical process of lock upgrade: 

 

 

49. What is a deadlock?

 

Deadlock refers to a blocking phenomenon caused by two or more processes due to competing resources or due to communication with each other. If there is no external force, they will not be able to continue. At this time, the system is said to be in a deadlock state or the system has a deadlock. These processes that are always waiting for each other are called deadlock processes. It is an error at the operating system level, short for process deadlock. It was first proposed by Dijkstra in 1965 when studying banker algorithms. It is one of the most difficult problems in computer operating systems and the entire concurrent programming field.

 

50. How to prevent deadlock?

 

Four necessary conditions for deadlock:

 

  • Mutually exclusive condition: the process does not allow other processes to access the allocated resources. If other processes access the resource, they can only wait until the process that owns the resource releases the resource

  • Request and hold conditions: After the process obtains a certain resource, it requests another resource, but the resource may be occupied by other processes. The request is blocked, but the resource obtained by itself is kept.

  • Inalienable condition: refers to the resources that the process has acquired. Before the use is completed, it cannot be deprived, and can only be released after use.

  • Loop waiting condition: refers to the process of forming a loop-to-end relationship between several processes after a deadlock occurs

 

These four conditions are necessary for deadlock. As long as the system has a deadlock, these conditions must be established, and as long as one of the above conditions is not met, no deadlock will occur.

 

Understand the cause of deadlock, especially the four necessary conditions for deadlock, you can avoid, prevent and release deadlock to the greatest extent possible.

 

Therefore, in the aspects of system design and process scheduling, pay attention to how to prevent these four necessary conditions from being established, how to determine a reasonable resource allocation algorithm, and avoid processes from permanently occupying system resources.

 

In addition, it is also necessary to prevent the process from occupying resources while in a waiting state. Therefore, reasonable planning should be given to the allocation of resources.


51. What is ThreadLocal? What are the usage scenarios?

 

Thread local variables are variables limited to the internal thread, which 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 management environment (such as a web server). In this case, the life cycle of the worker thread is longer than the life cycle of any application variable. Once any thread local variables are not released after the work is completed, there is a risk of memory leaks in Java applications.

 

52. Tell me about the underlying implementation principle of synchronized?

 

Synchronized can ensure that only one method can enter the critical section at a time when the method or code block is running, and it can also ensure the memory visibility of shared variables.

 

Every object in Java can be used as a lock. This is the basis of synchronized synchronization:

 

  • Common synchronization method, the lock is the current instance object

  • Static synchronization method, the lock is the class object of the current class

  • Synchronous method block, the lock is the object in brackets

53. What is the difference between synchronized and volatile?

 

  • The essence of volatile is to tell jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from main memory; synchronized is to lock the current variable, only the current thread can access the variable, other threads are blocked .

  • Volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level.

  • 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.

  • Variables marked with volatile will not be optimized by the compiler; variables marked with synchronized may be optimized by the compiler.

 

54. What is the difference between synchronized and Lock?

 

  • First, synchronized is a keyword built into java. At the jvm level, Lock is a java class;

  • Synchronized cannot determine whether to acquire the lock status, Lock can determine whether to acquire the lock;

  • synchronized will automatically release the lock (a thread will release the lock after executing the synchronization code; b exception will be released during the thread execution process), Lock needs to manually release the lock in the finally (unlock () method to release the lock), otherwise it is easy to cause the thread to die lock;

  • Two threads 1 and 2 using the synchronized keyword, if the current thread 1 acquires the lock, the thread 2 thread waits. If thread 1 is blocked, thread 2 will wait forever, and the lock will not necessarily wait. If the lock cannot be obtained, the thread can end without waiting;

  • Synchronized locks can be reentrant, uninterruptible, and unfair, while Lock locks can be reentrant, determinable, and fair (both)

  • Lock lock is suitable for the synchronization problem of a large number of synchronized codes, and synchronized lock is suitable for the synchronization problem of a small number of codes.

 

55. What is the difference between synchronized and ReentrantLock?

 

Synchronized is the same keyword as if, else, for, while, ReentrantLock is a class, which is the essential difference between the two. Since ReentrantLock is a class, it provides more and more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. The scalability of ReentrantLock than synchronized is reflected in several points: 

 

  • ReentrantLock can set the waiting time for acquiring the lock, so as to avoid deadlock 

  • ReentrantLock can obtain various lock information

  • ReentrantLock can flexibly realize multi-channel notification 

 

In addition, the locking mechanism of the two is actually different: the bottom of ReentrantLock calls Unsafe's park method to lock, and the synchronized operation should be the mark word in the object header.

56. Tell me about the principle of atomic?

 

The basic characteristic of the classes in the Atomic package is that in a multi-threaded environment, when multiple threads operate on a single (including basic type and reference type) variable at the same time, it is exclusive, that is, when multiple threads simultaneously value the variable When updating, only one thread can succeed, and the unsuccessful thread can continue to try like a spin lock, and wait until the execution is successful.

 

The core methods in the Atomic series of classes will call several local methods in the unsafe class. We need to know that one thing is the Unsafe class, whose full name is: sun.misc.Unsafe, this class contains a large number of operations on C code, including many direct memory allocation and atomic operation calls, and the reason why it is marked as non Safe is to tell you that a large number of method calls will have potential safety hazards and need to be used carefully, otherwise it will cause serious consequences. For example, when allocating memory through unsafe, if you specify certain areas yourself, it may cause some C ++ The pointer is out of bounds to other processes.

 

Published 9 original articles · liked 0 · visits 246

Guess you like

Origin blog.csdn.net/Fabri/article/details/105491882