In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the latest multi-threaded interview questions in 2021". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "what are the latest multi-threaded interview questions in 2021" together!
1) Take advantage of multi-core CPU
With the progress of industry, the current notebook, desktop and even commercial application servers are at least dual-core, 4-core, 8-core and even 16-core are not uncommon, if it is a single-threaded program, then 50% is wasted on dual-core CPU, and 75% is wasted on 4-core CPU. The so-called "multithreading" on a single-core CPU is false multithreading. At the same time, the processor will only process a section of logic, but the threads switch faster, looking like multiple threads running "at the same time." Multi-core CPU on the multi-thread is the real multi-thread, it can let you multi-segment logic work at the same time, multi-thread, can really play the advantages of multi-core CPU to achieve the purpose of making full use of CPU.
2) Prevention of obstruction
From the point of view of program efficiency, single-core CPU will not only play the advantage of multithreading, but will reduce the overall efficiency of the program because running multithreading on single-core CPU will cause thread context switching. but
If it's a single-core CPU, we still have to apply multithreading, just to prevent blocking. Imagine if a single-core CPU uses a single thread, and if that thread blocks, say reading some data remotely, the peer does not return for a long time without setting a timeout, then your entire program stops running before the data returns. Multithreading can prevent this problem, multiple threads running at the same time, even if the code execution of one thread reads data block, it will not affect the execution of other tasks.
3) Easy to model
This is another advantage that is not so obvious. Suppose there is a large task A, single-threaded programming, then we have to consider a lot, building the whole program model is more troublesome. However, if this large task A is broken down into several small tasks, task B, task C, and task D, respectively, program models are established, and these tasks are run separately through multiple threads, it is much simpler.
2. What is the difference between threads and processes?
The main difference between processes and threads is that they are different ways of managing operating system resources. Processes have independent address spaces, and when a process crashes, it does not affect other processes in protected mode, while threads are just different execution paths within a process. Threads have their own stacks and local variables, but there is no separate address space between threads, and the death of a thread is equivalent to the death of the entire process, so multi-process programs are more robust than multi-threaded programs, but when the process switches, it consumes more resources and is less efficient. But for some concurrent operations that require simultaneous execution and share certain variables, only threads can be used, not processes.
3. How many ways does Java implement threads?
1) Inheriting Thread class to realize multithreading
2) Implementation of Runnable interface to achieve multithreading
3) Use ExecutorService, Callable, Future to implement multithreading with return results
4. What is the difference between start() and run()?
Only when the start() method is called will the multi-thread feature be displayed, and the code in the run() method of different threads will be executed alternately. If you only call the run() method, then the code is still executed synchronously, and you must wait until all the code in the run() method of one thread has been executed before another thread can execute the code in its run() method.
5. How to terminate a thread? How to gracefully terminate threads?
Stop, not recommended.
6. How many states does a thread have in its lifecycle? How do they flow?
NEW: Undoubtedly represents a thread that has just been created and has not yet started.
RUNNABLE: indicates that the thread has triggered the start() mode call, the thread is officially started, and the thread is in the running state.
BLOCKED: indicates that the thread is blocked and waiting to acquire the lock. If the keywords such as synchronized and lock occupy the critical area, once the lock is acquired, the RUNNABLE state will continue to run.
WAITING: Indicates that the thread is in an unlimited waiting state, waiting for a special event to wake up again, such as a thread waiting through the wait() method waiting for a notify() or notifyAll() method, a thread waiting through the join() method waiting for the target thread to run and wake up, once the thread is awakened through the relevant event, the thread enters the RUNNABLE state to continue running.
TIMED_WAITING: Indicates that the thread enters a time-limited wait, such as sleep(3000), and waits for 3 seconds before the thread resumes running in the RUNNABLE state.
TERMINATED: indicates that the thread is terminated after execution. Note that once the thread is started via the start method, it can never return to the initial NEW state, and it can never return to the RUNNABLE state after the thread is terminated.
7. What is the difference between wait() and sleep() methods in a thread?
This question is often asked. Both the sleep method and the wait method can be used to give up the CPU for a certain time. The difference is that if the thread holds the monitor of an object, the sleep method will not give up the monitor of the object, and the wait method will give up the monitor of the object.
8. How many ways are there to synchronize multiple threads?
Synchronized keyword, Lock implementation, distributed lock, etc.
9. What is deadlock? How to avoid deadlock?
Deadlock is when two threads wait for each other to release an object lock.
10. How do multithreads communicate?
wait/notify
11. How does the thread get the return result?
Implementation of Callable interface.
What is the role of the violent keyword?
13. Create three threads T1, T2 and T3. How to ensure that they are executed in sequence?
Use the join method.
How do you control only 3 threads running at the same time?
with Semaphore.
15 Why use thread pools?
We know that without thread pools, every thread has to pass through new Thread.(xxRunnable).start() to create and run a thread. If there are few threads, this will not be a problem, but the real environment may open multiple threads to make the system and program achieve the best efficiency. When the number of threads reaches a certain number, it will exhaust the CPU and memory resources of the system, and it will also cause GC to collect and pause frequently, because each time a thread is created and destroyed, it will consume system resources. If you create threads for every task this is a big performance bottleneck. Therefore, thread multiplexing in the thread pool greatly saves system resources, and when the thread no longer has a task to process for a period of time, it will automatically destroy it instead of staying in memory.
16. Several commonly used thread pools and how they work.
What is the difference between submit() and execute() methods?
What is the difference between CyclicBarrier and CountDownLatch?
Two similar looking classes, both under java.util.concurrent, can be used to indicate that the code runs to a certain point, the difference between the two is:
1. After a thread of CyclicBarrier runs to a certain point, the thread stops running until all threads reach this point, and all threads run again;CountDownLatch is not, after a thread runs to a certain point, it only gives a certain value-1, and the thread continues to run 1.
2. CyclicBarrier can invoke only one task, CountDownLatch can invoke multiple tasks
3. CyclicBarrier can be reused, CountDownLatch cannot be reused, CountDownLatch cannot be reused if the count value is 0
19. What is a live lock, hunger, lockless, deadlock?
What is atomicity, visibility, order?
21. What is a guardian thread? What's the point?
What is a guardian thread? Corresponding to the daemon thread is the user thread. The daemon thread is the daemon user thread. When all the user threads are executed and finished, the daemon thread will end. That is, the daemon thread must be accompanied by the user thread. If there is only one daemon thread in an application, and there is no user thread, the daemon thread will naturally exit.
What happens when an exception occurs while a thread is running?
If the exception is not caught, the thread stops execution. Thread.UncaughtExceptionHandler is a built-in interface for handling sudden thread interrupts caused by uncaught exceptions. When an uncaught exception would cause a thread interrupt, the JVM uses Thread.getUncaughtExceptionHandler() to query the thread's UncaughtExceptionHandler and passes the thread and exception as arguments to the handler's uncaughtException() method for processing.
23. What is the use of the thread yield() method?
The Yield method suspends the currently executing thread object to allow other threads with the same priority to execute. It is a static method and only guarantees that the current thread will give up CPU use and cannot guarantee that other threads will be able to use CPU. The thread executing yield() may be executed immediately after entering the suspended state.
24 What is a reentry lock?
The so-called reentry lock refers to the unit of thread. After a thread acquires the lock of the object, this thread can acquire the lock on the object again, while other threads cannot.
25 What are the uses of Synchronized?
lock class, lock method, lock code block
What does the Fork/Join framework do?
Large tasks automatically disperse small tasks, execute concurrently, and merge the results of small tasks.
27. What exceptions can be caused by too many threads?
Too many threads can cause stack overflow and possibly heap exceptions.
28. Talk about thread-safe and unsafe collections.
The most commonly used Map collection in Java is HashMap, which is thread-unsafe. Consider the following two scenarios:
1, when used in the method of local variables, local variables belong to the current thread level variables, other threads can not access, so there is no thread safety unsafe problem. 1
2, when used in singleton object member variables? At this time, multiple threads come to access the same HashMap, and there is a thread safety problem for the same HashMap operation at this time.
29 What is CAS algorithm? What are the applications in multithreading.
How do I check if a thread has a lock?
java.lang.Thread#holdsLock method
31. What command is used to troubleshoot multithreading problems in Jdk?
jstack
32, thread synchronization need to pay attention to what?
Minimize the scope of synchronization and increase system throughput.
2, distributed synchronization lock meaningless, to use distributed lock.
3, to prevent deadlock, pay attention to the locking order.
33. What are the prerequisites for using the thread wait() method?
To be used in sync blocks.
34. What should be paid attention to when using Fork/Join framework?
If the task disassembly is very deep, the number of threads in the system will accumulate, resulting in a serious degradation of system performance; if the call stack of the function is very deep, it will lead to stack memory overflow;
35 How do I transfer data between threads?
36. What are the ways to ensure "visibility"?
synchronized and viotatile
37, say a few commonly used Lock interface to achieve lock.
ReentrantLock、ReadWriteLock
38 What is ThreadLocal? What are the application scenarios?
ThreadLocal provides local variables within a thread that work throughout the thread's life cycle, reducing the complexity of passing common variables between multiple functions or components within the same thread. Used to solve database connection, Session management, etc.
39 What is ReadWriteLock?
ReadWriteLock is a read-write lock interface, ReentrantReadWriteLock is a concrete implementation of ReadWriteLock interface, which realizes the separation of reading and writing. The read lock is shared, the write lock is exclusive, reading and reading will not be mutually exclusive, and reading and writing, writing and reading, and writing and writing will be mutually exclusive, thus improving the performance of reading and writing.
40 What is FutureTask?
FutureTask represents an asynchronous operation task. FutureTask can be passed a Callable with 1-body implementation class, which can wait for the result of this asynchronous operation, judge whether it has been completed, cancel the task, etc.
How do I wake up a blocked thread?
How does immutable objects help multithreading?
43. What does multithreaded context switching mean?
What thread scheduling algorithm is used in Java?
What is Thread.sleep(0)?
What is the Java memory model, which areas are shared by threads and which are not shared?
What are optimistic locks and pessimistic locks?
48, Hashtable size() method Why do you want to do synchronization?
49. Synchronization method or synchronization block, which is better?
50. What is a spin lock?
Spin locks are implemented by allowing the current thread to execute continuously within the loop body, entering critical sections only when the loop condition is changed by another thread.
Which is better, Runnable or Thread?
Java does not support multiple inheritance of classes, but allows you to implement multiple interfaces. So if you are inheriting other classes, and to reduce coupling between classes, Runnable is better.
What is the difference between notify and notifyAll in Java?
The notify() method does not wake up a particular thread, so it is only useful when a thread is waiting.
NotifyAll() wakes up all threads and allows them to fight for locks to ensure that at least one thread continues to run.
Why are wait/notify/notifyAll methods not in thread class?
Why are wait and notify methods called in sync blocks?
Why should you check wait conditions in a loop?
56. What is the difference between heap and stack in Java?
How do you get the thread stack in Java?
How do I create thread-safe singleton patterns?
59 What is a blocking method?
A blocking method means that the program waits for the method to complete and does nothing else, while the accept() method of ServerSocket waits for the client to connect. Block here refers to the current state before the call result returns.
The thread is suspended and does not return until the result is available. In addition, there are asynchronous and non-blocking methods that return before the task completes.
60. What happens when the thread pool queue is full when a task is submitted?
When the number of threads is less than maximumPoolSize, a new thread is created to process, and when the number of threads is greater than or equal to maximumPoolSize, a reject policy is executed.
Thank you for your reading. The above is the content of "What are the latest multi-threaded interview questions in 2021?" After studying this article, I believe you have a deeper understanding of what are the latest multi-threaded interview questions in 2021. The specific use situation still needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.