Multi-thread polymorphism implementation mechanism:

(1) Features and application scope of the three thread pools that can be created by Executors.

2. Implement runnable interface 3. Implement multithreading with returns using ExecutorService, Callable, and Future (after JDK5.0)Copy the code

(2) Multi-thread synchronization mechanism.

Add the synchronized keyword to the method signature of the method that needs to be synchronized. Synchronized blocks are used to synchronize code segments that need to be synchronized. Using JDK 5 provide Java. Util. Concurrent. Lock the lock objects in the package. Before a thread of synchronized code can execute it, it must first acquire permission to execute it, which in Java means acquiring a lock on a synchronized object (an object has only one lock); If the synchronization object's lock is taken by another thread, it will have to wait (the thread is blocked in the lock pool wait queue). Once the lock is picked up, he executes a synchronized code; The thread immediately returns the lock to the synchronized object after executing the synchronized code, and another thread waiting in the lock pool can take the lock and execute the synchronized code. This ensures that only one thread of synchronized code is executing at the same time.Copy the code

(3) Several available states of threads.

During execution, a thread can be in one of the following states: Runnable: A thread is ready to run, not necessarily immediately. Running: The process is executing the thread's code. Waiting: a thread is blocked, Waiting for external processing to complete. Sleeping: The thread is forced to sleep. The I/O operation is Blocked on I/O. Blocked on Synchronization: The process is Blocked until a lock is acquired. Dead: The thread has completed execution.Copy the code

(4) What is a deadlock?

A deadlock occurs when two processes are waiting for each other to complete before proceeding. The result is that both processes are stuck in an infinite wait.Copy the code

(5) How to ensure that N threads can access N resources without causing deadlocks?

With multiple threads, a very simple way to avoid deadlocks is to specify the order in which locks are acquired and force threads to acquire them in that order. Therefore, if all threads lock and release locks in the same order, there will be no deadlocks.Copy the code

(6) Explain multi-threading:

First, what is a thread? A thread is the execution path of a program, or the unit of control of a program. A process may contain one or more processes. When there are multiple execution paths for a process, the execution mode can be called multithreading. Threads can be roughly divided into ready (wait), execute (run), and block (block). The conversion of the three states is essentially caused in the process of snatching CPU resources. Under normal circumstances, CPU resources will not be occupied by threads alone, so multiple threads snatch resources during running, resulting in continuous conversion between threads in the above three states. And that's how multithreading works.Copy the code

(7) Thread lock object details:

Multithreading can run multiple tasks at the same time, but when multiple threads access shared data at the same time, it can cause data synchronization and even errors! So, do not use thread locks, which may cause errors. Application scenarios: I/ O-intensive operations require resource synchronization. Advantages and disadvantages: Advantages: Ensure resource synchronization Disadvantages: Slow expansion (deadlocks and recursive locks) If multiple threads want to call multiple objects, and thread A calls lock A and occupies object A, thread B calls lock B and occupies object B, thread A cannot call object B and thread B cannot call object A. So I waited. This causes thread "deadlocks". In the Threading module, there's also a class called RLock, called reentrant lock. The Lock object maintains a Lock and a counter object internally. The counter object counts the number of acquire times, allowing resources to be required more than once. Finally, when all rLocks are released, other threads can acquire resources. Rlock. acquire can be called more than once in the same thread, which can partially solve the deadlock problem. Lock = threading.lock (); lock= threading.rlock ();Copy the code

(8) Implementation of synchronization method:

1. Synchronization method

That is, methods modified by the synchronized keyword. Because every object in Java has a built-in lock, the built-in lock protects the entire method when you decorate it with this keyword. The built-in lock needs to be acquired before the method can be called, otherwise it is blocked. Public synchronized voidsave(){} Note: the synchronized keyword can also modify a static method that, if called, locks the entire classCopy the code

2. Synchronize code blocks

A block of statements decorated with the synchronized keyword. Synchronized (object){} Note: Synchronization is an expensive operation, so you should minimize the amount of synchronized content. It is often not necessary to synchronize the entire method; you can use a synchronized code block to synchronize key code.Copy the code

3. Use volatile to synchronize threads

The A. volatile keyword provides a lock-free mechanism for access to domain variables, b. Using volatile to modify a domain tells the virtual machine that the domain may be updated by another thread. D. volatile does not provide any atomic operations, nor can it be used to modify variables of final type. Asynchrony problems in multithreading occur primarily in reading and writing to the domain, and if you let the domain itself avoid this problem, you don't need to change the way you manipulate the domain. With final, lock-protected, and volatile domains, the problem of non-synchronization can be avoided.Copy the code

4. Use a reentrant lock to synchronize threads

A java.util.concurrent package has been added in JavaSE5.0 to support synchronization. The ReentrantLock class is a reentrant, mutually exclusive Lock interface that implements the Lock interface. It has the same basic behavior and semantics as synchronized methods and has extended its capabilities. ReentrantLock() : creates an instance of ReentrantLock lock() : acquires the lock unlock() : ReentrantLock() there is another constructor that can create a fair Lock, but it is not recommended because it can greatly reduce program performance. It is best to use neither and use a mechanism provided by the java.util.concurrent package that helps the user handle all lock-related code. B. Synchronized is used when the user needs it because it simplifies code c. If you need more advanced functionality, use the ReentrantLock class, and be careful to release the lock in time, otherwise a deadlock will occur, usually in the finally codeCopy the code

5. Use local variables for thread synchronization

If you use ThreadLocal to manage variables, each thread that uses the variable gets a copy of the variable, independent of each other, so that each thread can modify its own copy without affecting other threads. Get () : returns the value in the current thread copy of this thread-local variable initialValue() : returns the current thread of this thread-local variable"Initial value"
set(T value) : Sets the value of the current thread copy of this thread-local variable to value. B. the former is adopted as"Space for time"The latter adopts the method of"Time for space"6. Use blocking queues to implement thread synchronization the previous 5 synchronization methods are implemented in the bottom of the thread synchronization, but we in the actual development, should be as far as possible away from the bottom structure. Using the java.util.concurrent package, new in javaSE5.0, will help simplify development. This section mainly uses LinkedBlockingQueue<E> to synchronize threads. LinkedBlockingQueue<E> is a blocking queue of arbitrary scope based on connected nodes. LinkedBlockingQueue(); Create LinkedBlockingQueue with capacity integer.max_value. Put (E E) : Add an element to the end of the queue, block if the queue is full size() : Return the number of elements in the queue take() : Removes and returns the queue header element, or blocks if the queue is emptyCopy the code

7. Use atomic variables for thread synchronization

The fundamental reason for using thread synchronization is that operations on ordinary variables are not atomic. So what is atomic operation? Atomic operations refer to the operation of reading variable values, modifying variable values, and saving variable values as a whole - all at once or none at all. Utility classes that create atomic-type variables are provided in the Java util.concurrent.atomic package to simplify thread synchronization. Where the AtomicInteger table can update the value of int atomically, which can be used in applications (such as increments of counters atomically), but cannot be used to replace Integer; Extensible Number, which allows uniform access to tools and utilities that work with opportunistic Number classes. AtomicInteger(int initialValue) : create a new AtomicInteger addAddGet(int dalta) with a given initialValue: Add the given value to the current value atomically get() : Gets the current valueCopy the code

(9) The difference between sleep and wait methods

Come from different classes: The wait method is of the Object class, and the sleep method is of the Thread class. The usage of locks varies: primarily sleep does not release the lock, while wait releases the lock, allowing other threads to use the same step control block or method. Use scope: Wait, notify, and notifyAll can only be used in synchronous control methods or blocks, while sleep can be used anywhere.) Wake up: The thread that calls sleep() usually wakes up after a certain amount of sleep. Objects that call wait() must be awakened by notify() or notifyAll().Copy the code

Sleep method

The sleep method belongs to the Thread class. It means that a Thread is put to sleep, and after waiting for a certain amount of time, it automatically wakes up and enters the runnable state. It will not immediately enter the runnable state, because the Thread scheduling mechanism also needs time to restore the running of the Thread. It does not release all object locks held by it, so it does not affect the execution of other process objects. If your program does not catch InterruptedException, the thread will terminate in TERMINATED state. If your program catches the exception, it continues to execute the catch statement block (and possibly finally statement block) and subsequent code. Note that the sleep() method is static, that is, it only applies to the current object. It is wrong to send the t object to sleep through t.sleep(). It only causes the current thread to be slept, not t.Copy the code

Wait method

Wait is a member method of an Object. Once an Object calls the wait method, notify() and notifyAll() methods must be used to wake up the process. If a thread holds a synchronization lock on an object or objects, then after calling wait(), the thread releases all synchronized resources it holds, not only on the object on which wait() was called. The wait() method also generates InterruptedException when an interrupt() method is called by another object during the wait, and behaves the same way as sleep().Copy the code

(10) What is a daemon thread?

A daemon thread is a service thread, it's a service thread, it's a service thread, it's a service thread, that's what it does -- there's only one other thread, and that's a user thread. So there are two kinds of threads in Java. 1. Daemon threads, such as garbage collection threads, are the typical daemon threads. 2. User threads are custom threads in the application. Daemon threads are used to serve other threads. If all other threads (user-defined threads) have finished executing, including the main thread, then the JVM will exit (stop running). To put it another way, the JVM does not exit if a custom thread exists -- and the daemon thread cannot exit either, which means it still needs to run for garbage collection. User-defined threads 1. Threads in application programs are generally user-defined threads. 2. You can also customize daemon threads in your application code by calling the Thread setting method.Copy the code

(11) The difference between synchronous and asynchronous:

Sync

Synchronization is when a function call is made that does not return or continue until the result is received. By this definition, all methods in Java are called synchronously, since execution must wait until the result is reached. When we talk about synchronous and asynchronous, we generally refer to those tasks that require the cooperation of other terminals or require a certain amount of time to complete. Simply put, synchronization means that you have to do one thing at a time and wait until the previous one is done before you can do the next one.Copy the code

Async

Asynchrony is the opposite of synchronization, when an asynchronous procedure call is made, the caller can continue to perform subsequent operations without receiving the result. When this call is complete, the caller is generally notified through status, notifications, and callbacks. For asynchronous calls, the return of the call is not controlled by the caller. Take an example to briefly illustrate the difference between the two: synchronization: multiple Windows of the railway station sell train tickets. Suppose window A sells the 288th ticket. In this short process, no other window can sell the ticket or continue to sell the ticket. In plain English, when you see the word synchronized in a program, you lock a task, and when one thread enters, no other thread can be allowed to enter, that means synchronization. Asynchronous: When we use mobile phones to download a video, most of us will not wait for the video to finish downloading, but look at other things in the mobile phone during the downloading process, such as chatting with QQ or wechat, this is asynchronous, you do yours, I do mine, and do not interfere with each other. For example, it sells train tickets, if multiple Windows do not affect each other, go its own way, A window sold to the 288th, B window regardless of A window, since he also sold the 288th ticket, it will obviously make A mistakeCopy the code

— From the Interview guide of The Transwise Podcast