3. stop()Method directly terminates the thread, and**The lock held by this thread will be released immediately**. These locks are just used to maintain object consistency. If the write thread sucks in half of the data and forcibly terminates, the object will be written bad. At the same time, because the lock has been released, another read thread waiting for the lock will naturally read the inconsistent object. 2. General termination can be achieved by setting a boolean Flag to control whether the thread continues to execute. Or wait for the thread to finish executing automatically.
-
Thread interrupt
=====
-
Thread interrupt is an important thread cooperation mechanism.
-
Interrupt does not make the thread quit immediately, but sends a notice to the thread to tell the target thread that someone wants you to quit! As for how the target thread handles after receiving the notification, it is entirely up to the target thread to decide. This is very important, otherwise unconditional exit is no different from the stop() method.
-
There are three ways to deal with thread interrupts
-
public void Thread.interrupt() //Interrupt thread public void Thread.isInterrupted() //Judge whether it is interrupted public static boolean Thread.interrupted() //Judge whether it is interrupted and clear the current interrupt state
-
The interrupt() method is an instance method. It notifies the target thread of an interrupt, that is, sets the interrupt flag bit. The interrupt flag bit indicates that the current thread has been interrupted.
-
**isInterrupted() * * method is also an instance method. It determines whether the current thread has been interrupted (by checking the interrupt flag bit)
-
The static method interrupted() is also used to judge the interrupt status of the current thread, but it will clear the interrupt flag bit status of the current thread at the same time.
-
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(()->{ int i = 1; while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("Interrupt!"); break; } System.out.println("I'm working " + i++); Thread.yield(); } }); t1.start(); Thread.sleep(2000); t1.interrupt(); }
-
This looks very similar to the previous method of adding flag bits, but the interrupt function is more powerful. For example, if an operation like wait() or sleep() occurs in the loop body, it can only be identified by interrupt.
-
-
Thread sleep
==========
-
public static native void sleep(long millis) throws InterruptedException;
-
This method will make the current thread sleep for several times and throw an InterruptedException interrupt exception. InterruptedException is not a runtime exception, that is, the program must catch and handle it. This exception will occur if the thread is interrupted during sleep.
-
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(()->{ while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("Interrupt!"); break; } try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("Interrupted When Sleep"); Thread.currentThread().interrupt(); } Thread.yield(); } }); t1.start(); Thread.sleep(1000); t1.interrupt(); }
-
If the thread is interrupted during sleep, the program will throw an exception and enter exception handling. In the catch sentence, since the interrupt has been caught, we can immediately exit the thread, but we don't do so. Because * * maybe in this code, subsequent processing must be carried out to ensure data consistency and integrity** Therefore, the interrupt() method is executed to interrupt itself again and set the interrupt flag bit. Only by doing so can we find that the current thread has been interrupted after checking isInterrupted(). You can try to comment out the interrupt of catch for verification.
-
Thread. The sleep () method throws an exception due to an interrupt. At this time, it will clear the interrupt flag. If it is not handled, the interrupt cannot be avoided at the beginning of the next cycle. Therefore, in exception handling, set the interrupt flag bit again.
-
-
wait and notify
===================
-
wait and notify are not methods in the Thread class, but in the Object class, which means that any Object can call these two methods.
-
If a thread calls the wait() method, it will be counted into the waiting queue of the object object. There may be multiple threads in this waiting queue because the system runs multiple threads waiting for the same object at the same time. When notify() is called, it will randomly select a thread from the waiting queue and wake it up. But this choice is not fair. It is not that the thread waiting first will be selected first. This choice is completely random.
-
The notifyAll() method wakes up all threads in the waiting queue.
-
Both wait() and notify() methods must be included in the corresponding synchronized statement. Both wait() and notify() need to obtain a monitor of the target object first.
-
After the wait() method is executed, the monitor will be released. When the notify() method is re executed, * * the first thing to do is not to continue to execute the subsequent code, but to try to retrieve the monitor of the object** If it is temporarily unavailable, the thread must also wait for the monitor. When the monitor is successfully obtained, it can continue to execute in a real sense.
-
The difference between the wait() method and sleep() method is that wait releases the lock of the object, while sleep does not release the lock.
-
-
Suspend and resume
========================
-
The suspended thread must wait until the resume operation before continuing to specify
-
However, it has been marked as an abandoned method and is not recommended. Because suspend() will not release any resources while causing the thread to pause. At this time, any thread that wants to access the lock temporarily used by it will be implicated, resulting in failure to run normally. The suspended thread cannot continue operation until the resume() operation is performed on the corresponding thread. However, if the resume operation is executed before suspend, it is difficult for the suspended thread to continue.
-
If you want to implement suspend and resume, you can use wait and notify.
-
-
Wait for the thread to join and yield
==========================
-
The input of a thread may be very dependent on the output of one or more other threads. Therefore, this thread needs to wait for the dependent thread to finish executing before it can continue executing.
-
public final void join() throws InterruptedException public final synchronized void join(long millis) throws InterruptedException
-
The first join() method means to wait indefinitely. It will block the current thread until the target thread has finished executing.
-
The second join() gives a maximum waiting time. If the target thread is still executing after the given time, the current thread will continue to execute because it can't wait.
-
Join means to join. Therefore, if a thread wants to join another thread, the best way is to wait for it to go together.
-
public class JoinMain { public volatile static int i = 0; public static class AddThread extends Thread { @Override public void run() { for (i = 0; i < 1000000; i++); } } public static void main(String[] args) throws InterruptedException { AddThread at = new AddThread(); at.start(); at.join(); System.out.println(i); } }
-
In the main function, if you don't have to wait for AddThread with join(), the i you get is likely to be 0 or a very small number. Because AddThread has not finished executing, the value of i has been output. However, after using the join method, it means that the main thread is willing to wait for the completion of AddThread execution and move forward with AddThread. Therefore, when the join() returns, AddThread execution has been completed, so i is always 1000000;
-
The essence of join is to make the calling thread wait() on the current thread object instance.
-
if (millis == 0) { while (isAlive()) { wait(0); } }
-
As you can see, it calls the thread to wait on the current thread object. After execution, the waiting thread will * * call notifyAll() * * to notify all waiting threads to continue execution before exiting.
-
Therefore, it should be noted that methods such as wait() or notify() should not be used on the Thread object in the application, because it is likely to affect the work of the system API or be affected by the system API.
-
public static native void yield(); ```
- yield() this is a static method. Once executed, it causes the current thread to give up the CPU. After the current thread gives up the CPU, it will compete for CPU resources, but whether it can be allocated again is not certain.
-
-
volatile and Java Memory Model (JMM)
================================= 1. **Java Memory models are developed around atomicity, orderliness and visibility.** 2. Java Tell the virtual machine what special operations or keywords are used. Pay special attention to this place,**The optimization target instruction cannot be changed at will**. **volatile**Is one of them. 3. volatile: Volatile, unstable. 4. When volatile To declare a variable is to tell the virtual machine. This variable is most likely to be modified by some threads. To ensure that all threads within the scope of the application can "see" after this variable is modified. Virtual machine must adopt some special means to ensure the visibility of this variable. 5. volatile No**Replace lock. Nor can we guarantee the atomicity of some operations. volatile No guarantee i++Atomic operation.** 6. **volatile It can ensure the visibility and order of data.**
- Daemon thread
======================= 1. **Daemon thread**It is a special thread and the guardian of the system. It silently completes some systematic services in the background. For example, garbage collection threads, JIT Threads can be understood as daemon threads.
- thread priority
====== 1. Java Use 1~10 Indicates thread priority.**The higher the number, the higher the priority.******
- Synchronization method and synchronization block
========= 1. **Thread synchronization** -------- 1. Because multiple threads of the same process share the same storage space, it not only brings convenience, but also brings the problem of access conflict. In order to ensure the correctness of data access in the method, a lock mechanism is added during access**synchronized,**When a thread obtains the exclusive lock of an object and monopolizes resources, other threads must wait and decide whether to lock it after use. However, there are the following problems: 1. Holding a lock by one thread will cause all other threads that need the lock to hang. 2. In multi-threaded competition, locking and releasing locks will lead to more context switching and scheduling delays, resulting in performance problems 3. If a high priority thread waits for a low priority thread to release the lock, it will lead to priority inversion and performance problems. 2. keyword**synchronized**The function of is to realize the synchronization between threads. Its job is to lock the synchronized code, so that each time, only one thread can enter the synchronization block, so as to ensure the safety between threads. 1. Specify lock object: lock the given object, and obtain the lock of the given object before entering the synchronization code. 2. Direct action on instance method: it is equivalent to locking the current instance. Before entering the synchronization code, you need to obtain the lock of the current instance. 3. Direct action on static methods: it is equivalent to locking the current class. Enter the synchronization code block to obtain the lock of the current class. 3. **synchronized**Except for the guarantee**Thread synchronization,**It can also ensure the communication between threads**Visibility and order.**In terms of visibility, synchronized Can completely replace volatile,It's just not so convenient to use. In terms of order, because synchronized Limit that only one thread can access the synchronization block at a time. No matter how the code in the synchronization block is executed out of order, as long as the serial semantic consistency is guaranteed, the execution result is always the same. 2. Synchronization method ----
summary
No matter which company, it attaches great importance to high concurrency and high availability technology, foundation and JVM. Interview is a two-way choice process. Don't interview with fear, which is not conducive to your own play. At the same time, you should not only focus on the salary, but also see whether you really like the company and whether you can really get exercise. In fact, I have written so much, but my own summary is not necessarily applicable to everyone. I believe everyone will have these feelings after some interviews.
Finally, I sorted out some real interview questions, technical knowledge analysis tutorials, exchange and study with my colleagues, make common progress, and share some professional experience.
, pay attention to the JVM. Interview is a two-way choice process. Don't interview with fear, which is not conducive to your own play. At the same time, you should not only focus on the salary, but also see whether you really like the company and whether you can really get exercise. In fact, I have written so much, but my own summary is not necessarily applicable to everyone. I believe everyone will have these feelings after some interviews.
Finally, I sorted out some real interview questions, technical knowledge analysis tutorials, exchange and study with my colleagues, make common progress, and share some professional experience.
[external chain picture transferring... (img-gzODdKOJ-1630555360687)]