Home >Java >JavaInterview questions >Java multi-threading common interview questions
What is the difference between parallelism and concurrency? (Recommended study: java common interview questions)
Parallelism means that two or more events occur at the same time; and concurrency means that two or more events occur at the same time time interval occurs.
Parallelism is multiple events on different entities, and concurrency is multiple events on the same entity.
Process multiple tasks "simultaneously" on one processor, and process multiple tasks simultaneously on multiple processors. Such as hadoop distributed cluster.
So the goal of concurrent programming is to make full use of each core of the processor to achieve the highest processing performance.
What is the difference between thread and process?
In short, a process is the basic unit for program running 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 times and making it more efficient.
A thread is an entity of a process, the basic unit of CPU scheduling and dispatch, and a basic unit that is smaller than a program and can run independently. Multiple threads in the same process can execute concurrently.
What is a daemon thread?
The daemon thread is a service thread. To be precise, it serves other threads.
What are the ways to create a thread?
①. Inherit the Thread class to create a thread class
Define a subclass of the Thread class and override the run method of the class. The method body of the run method represents the thread requirements. Completed tasks. Therefore, the run() method is called the execution body.
Create an instance of the Thread subclass, that is, create a thread object.
Call the start() method of the thread object to start the thread.
②. Create a thread class through the Runnable interface
Define the implementation class of the runnable interface, and override the run() method of the interface. The method body of the run() method is also the thread Thread execution body.
Create an instance of the Runnable implementation class, and use this instance as the target of Thread to create a Thread object. This Thread object is the real thread object.
Call the start() method of the thread object to start the thread.
③. Create threads through Callable and Future
Create an implementation class of the Callable interface and implement the call() method. The call() method will serve 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 call() method of the Callable object.
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 ends.
What is the difference between runnable and callable?
This is a bit of a deep question, and it also shows the breadth of knowledge a Java programmer can acquire.
The return value of the run() method in the Runnable interface is void, and what it does is purely to execute the code in the run() method;
The call() in the Callable interface ) method has a return value and is a generic type. It can be used to obtain the results of asynchronous execution in conjunction with Future and FutureTask.
What are the statuses of threads?
Threads usually have five states, created, ready, running, blocked and dead.
Create status. When the thread object is generated, the start method of the object is not called, which means the thread is in the creation state.
Ready status. When the start method of the thread object is called, the thread enters the ready state, but at this time the thread scheduler has not set the thread as the current thread, and it is in the ready state at this time. After the thread runs, it will also be in the 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.
Blocking state. When a thread is running, it is suspended, usually to wait for a certain time to occur (for example, a certain resource is ready) before continuing to run. Sleep, suspend, wait and other methods can cause thread blocking.
Death state. If the run method of a thread ends or the stop method is called, the thread will die. For a thread that has died, you can no longer use the start method to make it ready.
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 execution opportunities to other threads. After the sleep time is over, the thread enters the ready state and Other threads compete together for CPU execution time.
Because sleep() is a static method, it cannot change the object's machine lock. When the sleep() method is called in a synchronized block, although the thread enters sleep, the object's machine lock is not released. 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 releases the machine lock of the object so that other threads can access it. , you can wake up waiting threads through notify, notifyAll methods
What is the difference between notify() and notifyAll()?
If a thread calls the wait() method of an object, the thread will be in the waiting pool of the object, and the threads in the waiting pool will not compete for the object's lock.
When a thread calls the object's notifyAll() method (wakes up all wait threads) or the notify() method (wakes up only one wait thread randomly), the awakened thread will enter the object's lock pool. , the threads in the lock pool will compete for the object lock.
In other words, after calling notify, only one thread will enter the lock pool from the waiting pool, and notifyAll will move all threads in the object waiting pool to the lock pool to wait for lock competition.
Threads with high priority have 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 Will return to the waiting pool.
The thread that competes for the object lock will continue to execute until the synchronized code block is executed, and it will release the object lock. At this time, the threads in the lock pool will continue to compete for the object lock.
What is the difference between thread run() and start()?
Each thread completes its operation through the method run() corresponding to a specific Thread object. The method run() is called the thread body. Start a thread by calling the start() method of the Thread class.
start() method to start a thread, truly realizing multi-threaded operation. At this time, there is no need to wait for the run method body code to be executed, and you can directly continue to execute the following code; at this time, the thread is in the ready state and is not running.
Then call the method run() through this Thread class to complete its running status. The method run() here is called the thread body, which contains the content of the thread to be executed. The Run method ends and the thread termination. The CPU then schedules other threads.
The run() method is in this thread. It is just a function in the thread, not multi-threaded. If you call run() directly, it is actually equivalent to calling an ordinary function. If you directly use the run() method, you must wait for the run() method to complete execution before executing the following code. Therefore, there is still only one execution path and there is no thread at all. characteristics, so the start() method should be used instead of the run() method during multi-thread execution.
What are the ways to create a thread pool?
①. newFixedThreadPool(int nThreads)
Create a fixed-length thread pool, and create a thread whenever a task is submitted until the maximum number of thread pools is reached. At this time The thread size will no longer change. When a thread terminates due to an unexpected error, the thread pool will replenish a new thread.
②. newCachedThreadPool()
Create a cacheable thread pool. If the size of the thread pool exceeds the processing demand, idle threads will be automatically recycled. When demand increases, idle threads can be automatically recycled. There is no limit on the size of the thread pool when adding new threads.
③. newSingleThreadExecutor()
This is a single-threaded Executor, which creates a single worker thread to perform tasks. If this thread ends abnormally, a new one will be created to replace it; it The characteristic is to ensure that tasks are executed serially according to the order in the queue.
④. newScheduledThreadPool(int corePoolSize)
Creates a fixed-length thread pool and performs tasks in a delayed or timed manner, similar to Timer.
What are the states of the thread pool?
The thread pool has 5 states: Running, ShutDown, Stop, Tidying, and Terminated.
Thread pool state switching frame diagram:
The submit() and execute() methods in the thread pool are What's the difference?
The parameters received are different
submit has a return value, but execute does not
submit facilitates Exception handling
In java program How to ensure the safety of multi-threaded operation?
Thread safety is reflected in three aspects:
Atomicity: Provides mutually exclusive access, and only one thread can operate on data at the same time, ( atomic, synchronized);
Visibility: One thread's modifications to main memory can be seen by other threads in time, (synchronized, volatile);
Orderliness: One thread observes other threads The order of execution of instructions in a thread, due to instruction reordering, is generally disorganized (happens-before principle).
What is the upgrade principle of multi-thread lock?
In Java, there are four lock states. The levels from low to high are: stateless lock, biased lock, lightweight lock and heavyweight lock state. These states will change with time. As the competition gradually escalates. Locks can be upgraded but not downgraded.
Illustrated process of lock upgrade:
What is a deadlock?
Deadlock refers to a blocking phenomenon caused by two or more processes competing for resources or communicating with each other during execution. Without external force, they will all Unable to proceed. 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.
is an error at the operating system level and is the abbreviation of process deadlock. It was first proposed by Dijkstra in 1965 when studying the banker's algorithm. It is the most difficult to deal with in computer operating systems and even in the entire field of concurrent programming. One of the questions.
How to prevent deadlock?
Four necessary conditions for deadlock:
Mutual exclusion condition: A process does not allow other processes to access the allocated resources. If other processes To access this resource, you can only wait until the process occupying the resource completes its use and releases the resource
Request and retention conditions: After the process obtains a certain resource, it makes a request for other resources, but the resource may be Occupied by other processes, this request is blocked, but it keeps the resources it has obtained.
Non-deprivable condition: refers to the resource that the process has obtained. It cannot be deprived before the use is completed. It can only be used after Release yourself after use
Loop waiting conditions: refers to the four conditions that form a head-to-tail loop waiting resource relationship between several processes after a process deadlock occurs
are necessary conditions for deadlock. As long as a deadlock occurs in the system, these conditions must be true. As long as one of the above conditions is not met, a deadlock will not occur.
Understanding the reasons for deadlock, especially the four necessary conditions for deadlock, you can avoid, prevent and eliminate deadlock to the greatest extent possible.
Therefore, in terms of system design, process scheduling, etc., pay attention to how to prevent these four necessary conditions from being established, how to determine a reasonable resource allocation algorithm, and to avoid processes permanently occupying system resources.
In addition, it is also necessary to prevent the process from occupying resources while it is in a waiting state. Therefore, the allocation of resources must be properly planned.
What is ThreadLocal? What are the usage scenarios?
Thread local variables are variables limited to the thread. They 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 especially careful when using thread-local variables in a managed environment (such as a web server), where the life cycle of the worker thread is longer than the life cycle of any application variables.
Once any thread-local variables are not released after the work is completed, Java applications are at risk of memory leaks.
Tell me about the underlying implementation principle of synchronized?
Synchronized can ensure that when a method or code block is running, only one method can enter the critical section at the same time. It can also ensure the memory visibility of shared variables.
Every object in Java can be used as a lock, which is the basis for synchronized to achieve synchronization:
Common synchronization method, the lock is the current instance object
Static synchronization method, lock It is the class object of the current class
Synchronized method block, and the lock is the object in the brackets
What is the difference between synchronized and volatile?
The essence of volatile is to tell the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from the main memory; synchronized locks the current variable and only the current thread can When accessing this variable, other threads are blocked.
volatile can only be used at the variable level; synchronized can be used at the variable, method, and class levels.
volatile can only realize the modification visibility of variables and cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables.
Volatile will not cause thread blocking; synchronized may cause thread blocking.
Variables marked volatile will not be optimized by the compiler; variables marked synchronized can be optimized by the compiler.
What is the difference between synchronized and Lock?
First of all, synchronized is a built-in keyword in java. At the jvm level, Lock is a java class;
synchronized cannot determine whether the lock status is acquired, but Lock can determine whether the lock is acquired;
synchronized will automatically release the lock (a thread will release the lock after executing the synchronization code; b thread will release the lock if an exception occurs during execution), Lock needs to be released manually in finally (the unlock() method releases the lock), Otherwise, it is easy to cause thread deadlock;
Use the synchronized keyword for two threads 1 and 2. If the current thread 1 obtains the lock, thread 2 will wait. If thread 1 is blocked, thread 2 will wait forever, and the Lock lock will not necessarily wait. If the lock cannot be obtained, the thread can end without waiting;
synchronized locks can be repeated Enterable, uninterruptible, and unfair, while Lock locks are reentrant, judgeable, and fair (both are possible);
Lock locks are suitable for synchronization problems with a large amount of synchronized code, and synchronized locks are suitable for small amounts of code. Synchronization issues.
What is the difference between synchronized and ReentrantLock?
synchronized is the same keyword as if, else, for, and while, and ReentrantLock is a class. This 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 various class variables. ReentrantLock is more extensible than synchronized. On several points:
ReentrantLock can set the waiting time for acquiring locks, thus avoiding deadlock
ReentrantLock can obtain information about various locks
ReentrantLock can Flexibly implement multiple notifications
In addition, the lock mechanisms of the two are actually different: ReentrantLock calls the Unsafe park method to lock at the bottom, while synchronized should operate on the mark word in the object header.
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 variable (including basic types and reference types) at the same time, they are exclusive, that is, when When multiple threads update the value of this variable at the same time, only one thread can succeed, and the unsuccessful thread can continue to try like a spin lock until the execution is successful.
The core methods in the Atomic series of classes will call several local methods in the unsafe class. One thing we need to know first 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 allocations and calls to atomic operations. The reason why it is marked as non Safe, I am telling you that a large number of method calls in this will have security risks, and you need to use it with caution, otherwise it will lead to serious consequences. For example, when allocating memory through unsafe, if you specify certain areas, it may lead to something similar to C. The pointer crosses the boundary to other processes.
The above is the detailed content of Java multi-threading common interview questions. For more information, please follow other related articles on the PHP Chinese website!