Home > Java > javaTutorial > What are the relevant knowledge points about Java thread interview questions?

What are the relevant knowledge points about Java thread interview questions?

WBOY
Release: 2023-04-23 23:07:06
forward
1147 people have browsed it

What are the relevant knowledge points about Java thread interview questions?

1. What is the difference between sychronied modified ordinary methods and static methods? What is visibility?

Object locks are used for object instance methods, or an object instance, and class locks are used for static methods of a class or class objects of a class. We know that there can be many object instances of a class, but each class has only one class object, so the object locks of different object instances do not interfere with each other, but there is only one class lock for each class.
One thing that must be noted is that in fact, class lock is only a conceptual thing and does not actually exist. Class lock actually locks the corresponding class object of each class. Class locks and object locks also do not interfere with each other.
Visibility means that when multiple threads access the same variable, if one thread modifies the value of the variable, other threads can immediately see the modified value.
Since all operations on variables by threads must be performed in the working memory and cannot directly read and write variables in the main memory, then for the shared variables V, they are first in their own working memory and then synchronized to the main memory. . However, it will not be flushed to the main memory in time, but there will be a certain time difference. Obviously, at this time, thread A's operation on variable V is no longer visible to thread B.
To solve the problem of shared object visibility, we can use the volatile keyword or lock.

2. What are the categories of locks?

What are the relevant knowledge points about Java thread interview questions?

3. The principle of CAS lock-free programming.

The current processors basically support the CAS() instruction, but the algorithms implemented by each manufacturer are different. Each CAS operation process contains three operators: a memory address V, An expected value A and a new value B. During operation, if the value stored at this address is equal to the expected value A, then the value at the address is assigned to the new value B, otherwise no operation is performed.
The basic idea of ​​CAS is that if the value at this address is equal to the expected value, give it a new value. Otherwise, do nothing but return the original value. Loop CAS is to continuously perform cas operations in a loop until it succeeds. We can also talk about three major problems with CAS.

4. Implementation principle of ReentrantLock.

The thread can repeatedly enter any code block that is synchronized with the lock it already owns. synchronized and ReentrantLock are both reentrant locks. In terms of implementation, every time a thread acquires a lock, it determines if the thread acquiring the lock is itself, and simply accumulates the counter. Each time the lock is released, the counter is decremented until the calculator returns to zero, indicating that the thread has been completely released. Lock. The bottom layer is implemented using AQS in JUC.

5. AQS principle.

is the basic framework used to build locks or other synchronization components. For example, ReentrantLock, ReentrantReadWriteLock and CountDownLatch are implemented based on AQS. It uses an int member variable to represent the synchronization status, and uses the built-in FIFO queue to complete the queuing work of resource acquisition threads. It is a variant implementation of the CLH queue lock. It can achieve 2 synchronization methods: exclusive and shared.
The main way to use AQS is inheritance. Subclasses inherit AQS and implement its abstract methods to manage synchronization status. The design of the synchronizer is based on the template method pattern, so if we want to implement our own synchronization tool class, we need to cover it. Several overridable methods, such as tryAcquire, tryReleaseShared, etc.
The purpose of this design is that synchronization components (such as locks) are user-oriented. It defines the interface for users to interact with synchronization components (for example, allowing two threads to access in parallel), hiding implementation details; synchronizers are user-oriented. is the implementer of locks. It simplifies the implementation of locks and shields underlying operations such as synchronization state management, thread queuing, waiting and waking up. This effectively isolates the areas that users and implementers need to focus on.
Internally, AQS maintains a shared resource state and uses the built-in FIFO to complete the queuing work of resource acquisition threads. The queue is composed of Node nodes one by one. Each Node node maintains a prev reference and next reference, which point to its own predecessor and successor nodes respectively, forming a two-ended doubly linked list.

6. The principle of Synchronized and the difference from ReentrantLock.

synchronized (this) principle: involves two instructions: monitorenter, monitorexit; let’s talk about the synchronization method. Judging from the decompilation results of the synchronization method, the synchronization of the method is not achieved through the instructions monitorenter and monitorexit. Compared with Ordinary methods have an additional ACC_SYNCHRONIZED identifier in the constant pool.
The JVM implements method synchronization based on this identifier: when the method is called, the calling instruction will check whether the ACC_SYNCHRONIZED access flag of the method is set. If it is set, the execution thread will first obtain the monitor. After the acquisition is successful, The method body can be executed, and the monitor can be released after the method is executed. During method execution, no other thread can obtain the same monitor object again.

7. What optimizations has Synchronized made

Introducing technologies such as spin lock, adaptive spin lock, lock elimination, lock coarsening, biased lock, lightweight lock, escape analysis and other technologies to reduce the cost of lock operations.

  • Escape analysis: If it is proved that an object will not escape outside the method or thread, this variable can be optimized:

  • Synchronization Elimination: synchronization Elimination, if an object will not escape the thread, the synchronization measures for this variable can be eliminated.

  • Lock elimination and coarse lock elimination: If the runtime compiler of the virtual machine detects that it is impossible to share data on some code that requires synchronization at runtime Competition will remove these locks.

  • Lock coarsening: Merge adjacent code blocks with the same lock. Eliminating meaningless lock acquisition and release can improve program running performance.

8. The difference and scope of Synchronized static and non-static locks.

Object locks are used for object instance methods or an object instance. Class locks are used for static methods of a class or class objects of a class. We know that there can be many object instances of a class, but each class has only one class object, so the object locks of different object instances do not interfere with each other, but there is only one class lock for each class.
One thing that must be noted is that in fact, class lock is only a conceptual thing and does not actually exist. Class lock actually locks the corresponding class object of each class. Class locks and object locks also do not interfere with each other.

9. Can volatile guarantee thread safety? What does it do on DCL?

There is no guarantee that the role of DCL is: volatile will ensure the visibility and ordering of modified variables, ensuring that in singleton mode, the execution order when creating an object must be

  1. Allocate memory space

  2. Instantiate the object instance

  3. Point the instance reference to the allocated memory space, at this time the instance has a memory address and is no longer null, thus ensuring that the instance is either null or a fully initialized object.

10. What is the difference between volatile and synchronize?

volatile is the most lightweight synchronization mechanism. Volatile guarantees the visibility when different threads operate on this variable, that is, if one thread modifies the value of a variable, the new value is immediately visible to other threads. However, volatile cannot guarantee the atomicity of operations, so composite write operations under multi-threads will cause thread safety issues.
The keyword synchronized can be used to modify methods or in the form of synchronized blocks. It mainly ensures that multiple threads can only have one thread in a method or synchronized block at the same time. It ensures that threads access variables Visibility and exclusivity, also known as built-in locking mechanisms.

11. What is a daemon thread? How do you exit a thread?

The Daemon (daemon) thread is a support thread because it is mainly used for background scheduling and support work in the program. This means that when there are no non-Daemon threads in a Java virtual machine, the Java virtual machine will exit. A thread can be set as a Daemon thread by calling Thread.setDaemon(true). We generally don't use it. For example, the garbage collection thread is the Daemon thread.
    Thread suspension: Either the run execution is completed, or an unhandled exception is thrown, causing the thread to end prematurely. The APIs corresponding to the thread Thread for suspending, resuming, and stopping operations are suspend(), resume(), and stop(). However, these APIs are out of date and are not recommended for use. Because it will cause the program to work in an uncertain state.
Safe suspension is when other threads interrupt a certain thread A by calling its interrupt() method. The interrupted thread determines whether it has been interrupted through the thread method isInterrupted(), or it can be called The static method Thread.interrupted() is used to determine whether the current thread is interrupted, but Thread.interrupted() will also rewrite the interrupt flag bit to false.

12. What are the differences between sleep, wait, and yield? How does the wait thread wake it up?

yield() method: causes the current thread to give up CPU ownership, but the time for giving up cannot be set. The lock resource will not be released. All threads executing yield() may be selected again by the operating system and executed immediately after entering the ready state.
After yield() and sleep() are called, the lock held by the current thread will not be released.
After calling the wait() method, the lock held by the current thread will be released, and after the current thread is awakened, it will compete for the lock again. The code behind the wait method will be executed only after the lock is competed.
Wait is usually used for interaction between threads, sleep is usually used to pause execution, and the yield() method causes the current thread to give up CPU ownership.
The wait thread uses notify/notifyAll() to wake up.

13. Is sleep interruptible?

sleep itself supports interrupts. If the thread is interrupted during sleep, an interrupt exception will be thrown.

14. Thread life cycle.

The status of threads in Java is divided into 6 types:

  1. Initial (NEW): A new thread object is created, but the start() method has not been called yet.

  2. Run (RUNNABLE): In Java threads, the two states of ready and running are generally called "running". After the thread object is created, other threads (such as the main thread) call the start() method of the object. The thread in this state is located in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU. It is in the ready state at this time. The thread in the ready state changes to the running state (running) after obtaining the CPU time slice.

  3. Blocked (BLOCKED): Indicates that the thread is blocked in the lock.

  4. Waiting (WAITING): The thread entering this state needs to wait for other threads to take some specific actions (notification or interruption).

  5. Timeout waiting (TIMED_WAITING): This state is different from WAITING, it can return by itself after the specified time.

  6. TERMINATED (TERMINATED): Indicates that the thread has completed execution.

What are the relevant knowledge points about Java thread interview questions?

15. What is ThreadLocal?

ThreadLocal is a special variable in Java. ThreadLocal provides a copy of the variable for each thread, so that each thread does not access the same object at a certain time, thus isolating the data sharing of data by multiple threads.
In terms of internal implementation, each thread has a ThreadLocalMap inside, which is used to save a copy of the variables owned by each thread.

16. Basic principles of thread pool.

During the development process, rational use of thread pools can bring 3 benefits.
First: Reduce resource consumption.
Second: Improve response speed.
Third: Improve the manageability of threads.

  1. If the number of threads currently running is less than corePoolSize, create a new thread to perform the task (note that performing this step requires acquiring a global lock).

  2. If the running threads are equal to or more than corePoolSize, add the task to the BlockingQueue.

  3. If the task cannot be added to the BlockingQueue (the queue is full), a new thread is created to process the task.

  4. If creating a new thread will cause the currently running thread to exceed maximumPoolSize, the task will be rejected and the RejectedExecutionHandler.rejectedExecution() method will be called.

17. There are three threads T1, T2, and T3. How to ensure that they are executed in order?

Can be implemented using the join method.

The above is the detailed content of What are the relevant knowledge points about Java thread interview questions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template