Understand threads
concept
A thread is the execution thread in the program. The Java virtual machine allows applications to run multiple execution threads concurrently.
Thread features
Has a state, which represents the state of a thread. At the same time, a thread in the JVM has only one state;
・NEW
Threads that have not been started yet (threads that have not been started since the start of the program run)
・RUNNABLE
A runnable thread that is running in the JVM, but it may be waiting for other resources, such as the CPU.
・BLOCKED
Blocking thread, waiting for a lock to allow it to continue running
・WAITING
Infinite wait (run again on a thread that relies on letting it enter that state to perform a specific operation)
・TIMED_WAITING
Timed waiting (run again on a thread that relies on letting it enter that state for a specific operation within a specified waiting time)
・TERMINATED
Exited thread
Have priority and determine the execution order of threads;
An integer between 1 and 10, the default value is 5. The higher the value, the higher the chance of execution, and priority does not determine the execution order of the thread.
The priority of the child thread is the same as that of the parent thread by default.
Note that the JVM will stop executing all threads when:
The exit () method of Runtime (runtime) is called and the call of the method is allowed by Security Manager;
All "non-daemon threads" have stopped running (regardless of whether they stop normally or a stop);
Can be marked as a daemon (Daemon)
The child thread of the daemon thread is still the daemon thread;
The daemon thread is also the "backend thread", which is generally used to execute background tasks, while the user thread generally executes user-level tasks.
Methods to terminate thread
1. Use the exit flag to make the thread exit normally, that is, the thread terminates after the run method is completed.
When the run method is executed, the thread will exit. But sometimes the run method never ends. For example, using threads to listen to client requests in server programs, or other tasks that require loop processing. In this case, these tasks are usually placed in a loop, such as while loop. If you want the loop to run forever, you can use while(true){...} to handle it. However, if you want to make the while loop exit under a certain condition, the most direct way is to set a boolean type flag and control whether the while loop exits by setting this flag to true or false. Here is an example of terminating a thread using the exit flag.
FlagExitThread.java
package com.rainmonth;/*** Created by RandyZhang on 2017/3/23.*/public class FlagExitThread extends Thread {public volatile Boolean isExit = false;public FlagExitThread(String name) {super(name);}@Override public void run() {while (!isExit) {System.out.println("I'm running");}}}DemoClient.java
package com.rainmonth;/*** Created by RandyZhang on 2017/3/23.*/public class DemoClient {public static void main(String[] args) {System.out.println("Elegant Terminal Thread Instance");exitByFlag();// exitByInterrupt();}private static void exitByFlag() {FlagExitThread flagExitThread = new FlagExitThread(FlagExitThread.class.getSimpleName());flagExitThread.start();try {Thread.sleep(1000);flagExitThread.isExit = true;flagExitThread.join();System.out.println("Thread Exit");}catch (InterruptedException e) {e.printStackTrace();}}private static void exitByInterrupt() {FlagExitThread flagExitThread = new FlagExitThread(FlagExitThread.class.getSimpleName());System.out.println("flagExitThread running...");flagExitThread.start();try {Thread.sleep(1500);System.out.println("flagExitThread interrupted...");flagExitThread.interrupt();Thread.sleep(1500);System.out.println("stop application...");}catch (InterruptedException e) {e.printStackTrace();}}}Output result:
Print a bunch of I'm running after the thread exits.
2. Use the stop method to forcefully terminate the thread (this method is not recommended, because stop is the same as suspend and resume, and may also have unpredictable results).
Shows calling stop() method. The description of stop() in the source code is as follows:
/** This method is inherently unsafe. Stopping a thread with* Thread.stop causes it to unlock all of the monitors that it* has locked (as a natural consequence of the unchecked* <code>ThreadDeath</code> exception propagating up the stack). If* any of the objects previously protected by these monitors were in* an inconsistent state, the damaged objects become visible to* other threads, potentially resulting in arbitrary behavior. Many* uses of <code>stop</code> should be replaced by code that simply* modify some variable to indicate that the target thread should* stop running. The target thread should check this variable* regularly, and return from its run method in an orderly fashion* if the variable indicates that it is to stop running. If the* target thread waits for long periods (on a condition variable,* for example), the <code>interrupt</code> method should be used to* interrupt the wait.*/
The general meaning is that the insecurity of the method is inherent. Calling stop() to terminate a thread will release all monitors it has locked (this will cause ThreadDeath exception propagating upward along the stack to be checked to be thrown). If there is inconsistency in objects previously protected by these released monitors and these objects are visible to other threads, this will lead to some unexpected consequences. What should stop operations be replaced by code that only needs to modify certain code to indicate that the target thread should stop running (method 1 is this way). If the target thread waits for a certain condition (such as a certain condition variable) for a long time, we should use the interrupt method to interrupt the wait (this is the method of method 3).
3. Use interrupt method to interrupt thread.
interrupt literally means terminating, but don't try to terminate the thread by calling interrupt, because sometimes even if you call the method, the thread will continue to execute. You can comment out the exitByFlag() above, enable the exitByInterrupt() method, and find that the interrupt() method is called in time, and I'm running... (the results of different systems and CPUs may be different). It can be seen that it is not safe to use interrupt method.
Summarize
According to the above analysis, the most recommended method is the first one. We can set flags using shared variables and send out signals to inform the thread that it must terminate. Of course, we must ensure that the operations of this shared variable are synchronous.
The above is all the content of this article about the Java termination thread instance and the stop() method source code reading. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!