preface
It’s hard, and with graduation season just around the corner, whether it’s interns or executives looking to jump ship, questions about multithreading and concurrency are an essential part of any Java interview. Therefore, this article is my latest answer and summary of the interview questions, and I hope it will be helpful to students who want to enter BAT. Due to its long length, I suggest that you collect it and read it carefully
What is thread-safe and thread-unsafe?
Popular say: lock is thread safe, not lock is thread unsafe
Thread safety
Thread safety: When multi-threaded access, the locking mechanism is adopted. When one thread accesses a certain data of the class, it is protected and cannot be accessed by other threads. Other threads can use the data until the thread finishes reading. There will be no data inconsistencies or data contamination. The same instance object of a thread-safe counter class can be used by multiple threads without miscalculation. Obviously you can split collection classes into two groups, thread-safe and non-thread-safe. Vector is thread-safe using a synchronous approach, whereas ArrayList, like it, is not thread-safe.
Thread insecurity
Thread unsafe: Data access protection is not provided. Multiple threads may change data successively, resulting in dirty data. If your code is in a process that has multiple threads running at the same time, those threads may be running the code at the same time. If the result of each run is the same as the result of a single thread run, and the values of other variables are the same as expected, it is thread-safe.
Thread-safety issues are caused by global and static variables. If there are only reads and no writes on a global variable or static variable per thread, the global variable is generally thread-safe. If you have multiple threads performing write operations at the same time, you generally need to consider thread synchronization, otherwise it may affect thread safety.
2. What is a spin lock?
The basic concept
(1) Spin lock is a low-level synchronization mechanism in SMP architecture. (2) When thread A wants to acquire A spin lock that is held by another thread lock, thread A spins in A loop to check if the lock is available.
Spin-locks need to be noted:
(1) Since spinning does not release the CPU, the thread holding the spin lock should release the spin lock as soon as possible, otherwise the thread waiting for the spin lock will keep spinning there, wasting CPU time. (2) The thread holding the spin lock should release the spin lock before sleep so that other threads can acquire the spin lock. Implement spin locking
(3) A simple while will do the trick.
Current JVM implementations use CPU to spin, and if doNotify is not called for a long time, the doWait method spins all the time, which can be too CPU consuming.
3. Three elements of concurrent programming?
(1) atomicity
Atomicity refers to one or more operations that are either all performed without interruption by other operations, or none performed at all.
(2) Visibility
Visibility means that when multiple threads operate on a shared variable, when one thread makes changes to the variable, the other threads can see the changes immediately.
(3) Orderliness
Orderliness, that is, the order in which the program is executed is the order in which the code is executed.
4. What are the ways to achieve visibility?
Synchronized or Lock: ensure that only one thread at a time obtains the Lock execution code, and refresh the latest value to the main memory before releasing the Lock to achieve visibility.
5. The value of multithreading?
(1) Give play to the advantages of multi-core CPU
Multi-threaded, can really play the advantages of multi-core CPU, to make full use of the PURPOSE of CPU, using multi-threaded way to complete several things at the same time without mutual interference.
(2) Prevent blocking
From the point of view of program efficiency, single-core CPU will not give full play to the advantages of multithreading, but will cause the thread context switch because of running multithreading on single-core CPU, and reduce the overall efficiency of the program. But with 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 data remotely, and the peer doesn’t return and doesn’t set a timeout, your entire program will stop running before the data comes back. Multithreading prevents this problem. Multiple threads are running at the same time, and even if the code in one thread is blocked in reading data, it does not affect the execution of other tasks.
(3) Easy to model
This is another advantage that is not so obvious. Let’s say you have A big task A, single-threaded programming, and it’s A lot to think about, and it’s A lot of trouble to model the entire program. However, if the big task A is broken down into several small tasks, task B, task C and task D, respectively build the program model, and run these tasks separately through multi-threading, it will be much simpler.
What are the ways to create a thread?
(1) Create a Thread class by inheriting the Thread class, (2) create a Thread class through the Runnable interface, (3) create a Thread through Callable and Future, and (4) create a Thread pool
How do you compare the three ways to create threads?
(1) Use Runnable, Callable interface to create multithreading.
The advantage is that thread classes simply implement the Runnable or Callable interfaces and can inherit from other classes. In this way, multiple threads can share the same target object, so it is very suitable for the situation of multiple same threads to deal with the same resource, so that the CPU, code and data can be separated, forming a clear model, which better reflects the idea of object-oriented. The downside: the programming is a bit complicated, and if you want to access the currentThread, you must use the thread.currentthread () method.
(2) Create multiple threads by inheriting Thread class
The advantage is that it is easy to write. If you need to access the currentThread, you can use this to get the currentThread without using thread.currentthread (). The disadvantage is that Thread classes already inherit from Thread, so they cannot inherit from other parent classes.
(3) Difference between Runnable and Callable
The Callable specified (overridden) method is call() and the Runnable specified (overridden) method is run(). Callable tasks return values after execution, while Runnable tasks do not. The Call method can throw an exception, but the run method cannot. Running the Callable task retrieves a Future object that represents the result of the asynchronous calculation. It provides a way to check that a calculation is complete, wait for it to complete, and retrieve the results of the calculation. By using the Future object, you can know the execution status of the task, cancel the execution of the task, and obtain the execution result.
Thread state flow diagram
The life cycle of a thread and its five basic states:
Java threads have five basic states
(1) New state (New) : When the Thread object pair is created, it enters the New state, such as: Thread t = New MyThread(); (2) ready state (Runnable) : when the thread object’s start() method is called (t.start();) , the thread enters the ready state. When a thread is in the ready state, it is ready to be executed by the CPU, not when t.start() is executed. (3) Running state (Running state) : when the CPU starts to schedule the thread in the ready state, then the thread can actually execute, that is, enter the Running state. Note: Ready state is the only entry into the running state, that is, in order to enter the running state execution, the thread must first be in the ready state; (4) Blocked state: The thread in the running state temporarily gives up the right to use the CPU for some reason and stops execution. At this time, it enters the Blocked state. Until it enters the ready state, it has the chance to be called by the CPU again to enter the running state.
According to different causes of blocking, blocking states can be divided into three types:
A. Waiting to block: A thread in the running state executes wait() to make it enter the waiting state; B. Synchronized blocking — if a thread fails to acquire a synchronized lock (because the lock is occupied by another thread), it enters the synchronized blocking state; C. Other blocking – A thread enters a blocking state by calling its sleep() or join() or by issuing an I/O request. When the sleep() state times out, when the join() wait thread terminates or times out, or when I/O processing is complete, the thread goes back to the ready state.
(5) Dead state: the thread finishes executing or exits the run() method due to an exception, and the thread ends its life cycle.
What is a thread pool? What are the ways to create it?
A thread pool is a pool of threads that are created in advance. If there is a task that needs to be processed, the threads in the pool will handle the task, and then the thread will not be destroyed. Instead, it will wait for the next task. Since creating and destroying threads consumes system resources, consider using thread pools when you want to create and destroy threads frequently to improve system performance.
Java provides a Java. Util. Concurrent. The realization of the Executor interface is used to create a thread pool.
11. Create four thread pools:
(1) newCachedThreadPool creates a cacheable thread pool. (2) newFixedThreadPool creates a fixed length thread pool, which controls the maximum number of concurrent threads. (3) newScheduledThreadPool Creates a thread pool of fixed length to support scheduled and periodic task execution. (4) newSingleThreadExecutor creates a single threaded thread pool that only uses a single worker thread to perform tasks.
12. What are the advantages of thread pools?
(1) Reuse existing threads to reduce the overhead of object creation and destruction. (2) It can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, and avoid excessive resource competition and blockage. (3) Provide timing execution, periodic execution, single thread, concurrency control and other functions.
Because space does not allow, only the questions are shown below, and documents requiring multi-threaded interview questions (including answers) can be downloaded here
13. What are the common concurrency utility classes? The difference between CyclicBarrier and CountDownLatch What is the Future of CAS? 21. AQS supports two synchronization modes: What is ReadWriteLock? What is FutureTask? What is synchronized and ReentrantLock 27. What is the difference between synchronized and wait? 29. What is ThreadLocal? What’s the use? Why wait() and notify()/notifyAll() are called in synchronized blocks What is the concurrency of ConcurrentHashMap? How to find which thread uses the longest CPU in Linux? How do immutable objects help multithreading? What is context switching for multithreading? What is the Thread scheduling algorithm used in Java? What is Thread Scheduler and Time Slicing? Java 45, Singlecase Thread safety 46, What does Semaphore do for execaphore? Which thread will call the static block or the synchronized method? What exceptions can be caused by too many Java threads?
conclusion
These multi-threaded questions, some from the major websites, some from their own thinking. There may be some problem online, there may be some questions the corresponding answers and, also may be a little fellow netizens also are seen, but the focus of this writing is that all problems will be according to own understanding to answer again, don’t go to the online answer, so there may be some problems about wrong, can correct hope you feel free to comment. Recently in view of the Internet company interview asked knowledge points, summed up the Java programmer interview involves most of the interview questions and answers to share with you, I hope to help you review before the interview and find a good job, but also save you on the Internet to search for information time to learn. Full Version of the Java InterviewJAVA backend test integration
Content covers: Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, SpringBoot, SpringCloud, RabbitMQ, Kafka, Linux and other technology stacks.
The original link: blog.csdn.net/VX133084144…