Multi-threading technology is so widely used in Internet technology that almost all back-end technology interviewers have to make all sorts of difficulties in the use and principles of concurrent programming. As a senior technical interviewer in the Internet technology industry who has attacked hundreds of [please allow me to exaggerate], I have read the disappointing departure of countless lonely people. I feel slightly embarrassed. I present this article and I hope that readers Try to force yourself behind and never fail!
If you feel that the article is helpful to you, you can give it a bit of attention and give the author a little encouragement.
A thread is the smallest unit that the operating system can schedule operations on. It is included in the process and is the actual unit of operation in the process. It can use multiple threads to speed up operations.
For example, if a thread completes a task for 100 milliseconds, it takes only 10 milliseconds to complete the task with ten threads.
What is multithreading?
Multithreading: Concurrent technology that implements multiple threads from software or hardware.
The benefits of multi-threading:
Using multi-threading can put tasks that take a long time in the program into the background, such as downloading of images and videos.
Take advantage of multi-core processors, concurrent execution allows the system to run faster, smoother, and have a better user experience
Disadvantages of multithreading:
A large number of threads reduce the readability of the code;
More threads require more memory space
When multiple threads compete for the same resource, be aware of thread safety issues.
The five states of the thread (five states, create, ready, run, block, and die)?
Threads typically have five states, Create, Ready, Run, Block, and Die.
The first is the creation status. The thread object is generated, and the object's start method is not called. This is the thread's creation state.
The second is the ready state. When the thread object's start method is called, the thread enters the ready state, but at this point the thread scheduler has not set the thread as the current thread, and is now in the ready state. After the thread runs, it will be in a ready state after returning from waiting or sleeping.
The third is the operating status. The thread scheduler sets the thread in the ready state to the current thread. At this point, the thread enters the running state and starts running the code in the run function.
The fourth is the blocking state. When the thread is running, it is paused, usually to wait for a certain time (for example, a resource is ready) to continue running. Sleep, suspend, wait, and other methods can lead to thread blocking.
The fifth is death. If a thread's run method ends or the stop method is called, the thread dies. For dead threads, the start method can no longer be used to make it ready
What is CAS?Abbreviation for CAS (compare and swap), translated into Chinese for comparison and exchange.
CAS does not use the JVM, directly use the Java local JNI (Java NaTIve Interface for JAVA native calls), directly call the CPU's cmpxchg (assembler instructions) instructions.
Using the CPU's CAS instruction, JNI is also used to implement Java's non-blocking algorithm to implement atomic operations. Other atomic operations are done using similar features.
The entire java.uTIl.concurrent is built on the CAS, so for the synchronized blocking algorithm, JUC has greatly improved performance.
CAS is an optimistic locking technique. When multiple threads try to use the CAS to update the same variable at the same time, only one of the threads can update the value of the variable, while other threads fail. The failed thread is not suspended but is instead Tell this competition to fail and try again.
CAS application
CAS has 3 operands, a memory value of V, an old expected value of A, and a new value of B to be modified. If and only if the expected value A and the memory value V are the same, modify the memory value V to B, otherwise do nothing.
CAS advantages
Ensure read-modify-write operations on memory are atomic operations
CAS disadvantages
Although CAS solves atomic operations very efficiently, CAS still has three major problems. ABA problem, long cycle time overhead and can only guarantee atomic operations of a shared variable
What is AQS?AbstractQueuedSynchronizer, short for AQS, is a framework for building locks and synchronization containers. In fact many classes in the concurrent package are based on AQS builds, such as ReentrantLock, Semaphore, CountDownLatch, ReentrantReadWriteLock, FutureTask and so on. AQS solves a lot of detail problems in designing synchronous containers.
AQS uses a FIFO queue to represent the thread waiting for the lock. The queue head node is called the "sentinel node" or "dummy node" and it is not associated with any thread. The other nodes are associated with the waiting thread, and each node maintains a wait status waitStatus.
Pessimistic lock
Java prior to JDK1.5 was synchronized using the synchronized keyword. This use of a consistent locking protocol to coordinate access to the shared state, can ensure that regardless of which thread holds the shared variable lock, exclusive use of Access these variables. Exclusive lock is actually a pessimistic lock, so it can be said that synchronized is a pessimistic lock.
Optimistic lock
Optimistic locking (opTimisTIc Locking) is actually an idea. For pessimistic locking, the optimistic lock hypothesis assumes that data will not cause conflicts under normal circumstances. Therefore, when the data is submitted for update, the data will be tested for conflict or not. If a conflict is found, the user error is returned. The information allows the user to decide how to do it.
What is the difference between concurrent programming (concurrency) and parallellism?
Concurrency and parallellism are:
Explanation 1: Parallelism refers to two or more events occurring at the same time; concurrent refers to two or more events occurring at the same time interval.
Explanation 2: Parallelism is multiple events on different entities. Concurrency is multiple events on the same entity.
Explanation 3: Deal with multiple tasks "simultaneously" on one processor and handle 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.
Want to understand more multi-threaded knowledge points, you can add the group 650385180, multi-threaded learning materials and multi-threaded face-question summary in the group's shared area for everyone to download for free.
How to wake a blocked thread?
If the thread is blocking due to calling wait(), sleep(), or join() methods, it can interrupt the thread and wake it up by throwing an InterruptedException; if the thread encounters IO blocking, nothing can be done because IO is the operating system Implementation, Java code does not have direct access to the operating system.
How to detect deadlock? How to prevent deadlock?
The so-called deadlock: refers to two or more processes in the implementation process, due to competition for resources caused by a phenomenon of mutual wait, if no external role, they will not be able to proceed. The system is deadlocked at this time
In layman's terms, a state in which two or more processes are blocked indefinitely and wait for each other
The reason for the deadlock?
1. Deadlock due to competing resources: When the number of resources shared by multiple processes in the system is insufficient to meet the needs of all processes, it will cause competition for resources and deadlock
2. Deadlock in the wrong sequence of process advancement
The four necessary conditions for deadlock:
Exclusive conditions: 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 completes the use of the resource.
Request and hold conditions: After the process acquires a certain resource, it sends a request to other resources, but the resource may be occupied by other processes. This request is blocked, but it keeps its own resources.
Inalienable condition: refers to the resources that the process has acquired. It cannot be deprived until it is used, and can only be released after use.
Loop waiting condition: refers to a round-robin waiting resource relationship formed between processes after deadlock occurs in a process.
These four conditions are necessary for deadlock. As long as the system is deadlocked, these conditions must be established, as long as the above conditions
If it is not satisfied, there will be no deadlock.
Detect deadlockThere are two containers, one for holding the lock that the thread is requesting and one for holding the lock that the thread already holds. Before each lock, the following tests are performed:
Detects whether the currently requesting lock is already held by other threads, and if so, finds those threads
Traverse the thread returned in the first step, check whether the lock it holds is being requested by any one of the threads, if the second step returns true, indicating a deadlock
Deadlock release and prevention:
Understand the reasons for deadlock, especially the four necessary conditions for deadlock, you can avoid, prevent and release the deadlock to the greatest extent possible.
Therefore, in the system design, process scheduling and other aspects pay attention to how to prevent the establishment of these four necessary conditions, how to determine the rational allocation of resources, algorithms, to avoid the process permanently occupy system resources.
In addition, it is also necessary to prevent processes from occupying resources while they are waiting. Therefore, reasonable allocation of resources should be given.
Want to understand more multi-threaded knowledge points, you can add the group 650385180, multi-threaded learning materials and multi-threaded face-question summary in the group's shared area for everyone to download for free.
What is atomic operation? What are the atomic classes in the Java Concurrency API?
What is the Executors framework?
What is a blocking queue? How to use blocking queues to implement a producer-consumer model?
What is Callable and Future?
What is FutureTask?
What is the implementation of synchronous containers and concurrent containers?
What is a multithreaded context switch?
ThreadLocal design concept and role?
ThreadPool usage and advantages?
Adding groups for more multi-threaded knowledge points and interview questions
Other things in the Concurrent package: ArrayBlockingQueue, CountDownLatch, and so on.
The difference between synchronized and ReentrantLock?
What is the role of Semaphore?
What is the Lock interface in the Java Concurrency API? What is the advantage of comparing it to sync?
to sum upSome conclusions about the Java multithreading interview technical point have been finished, limited by my vision, so it may not be very comprehensive, if you have different opinions, you can share it out, communicate together, if you want to know more about multi-threading technology Knowledge points, you can add the above group, hope to help friends and children's shoes in the development of the industry, spend less time in forum blogs and other places to find information, and spend a limited time, really spent on learning.
Absolute rotary Encoder measure actual position by generating unique digital codes or bits (instead of pulses) that represent the encoder`s actual position. Single turn absolute encoders output codes that are repeated every full revolution and do not output data to indicate how many revolutions have been made. Multi-turn absolute encoders output a unique code for each shaft position through every rotation, up to 4096 revolutions. Unlike incremental encoders, absolute encoders will retain correct position even if power fails without homing at startup.
Absolute Encoder,Through Hollow Encoder,Absolute Encoder 13 Bit,14 Bit Optical Rotary Encoder
Jilin Lander Intelligent Technology Co., Ltd , https://www.jilinlandermotor.com