Home  >  Article  >  Java  >  Several ways and example analysis of Java thread termination

Several ways and example analysis of Java thread termination

WBOY
WBOYforward
2023-04-27 10:31:071636browse

Several ways and example analysis of Java thread termination

Question analysis

The answer is C

A: The thread uses the sleep() method to suspend the thread for a period of time, not to terminate it

B: When creating a new thread, it has no effect on the previous thread.

C: An exception is thrown and the thread terminates.

D: It is not a termination, but a preemption. The process is The most basic unit of resource allocation. Different threads created by the same process share these resources. When a thread has a higher priority, it will seize the resources of other threads, causing other threads to have no resources available, which will cause blocking

Three reasons for the end of the thread

1. The run method is executed and the thread ends normally

2. The thread throws an uncaught Exception or Error

3 , Directly call the Stop method of the thread to end the thread (not recommended, it can easily lead to deadlock)

Detailed analysis

Three ways to end the thread

①Use the flag bit Exit the thread

②Use the stop method to forcefully terminate the thread

③Use interrupt to terminate the thread

1. Use the flag bit to launch the thread

General run() method After execution, the thread will end normally. However, some threads are often servo threads. They need to run for a long time, so they need to use a variable to control the loop

defines an exit flag exit. When exit is true, the while loop exits, and the default value of exit is false. When defining exit, use A Java keyword volatile is added. The purpose of this keyword is to synchronize exit. Only one thread can modify the value of exit at the same time.

public class ThreadSafe extends Thread {
  public volatile boolean exit = false; 
    public void run() { 
     while (!exit){
     //do something
     }
  } 
}

2. Use the stop method to forcefully terminate the thread

You can directly use thread.stop() in the program to forcibly terminate the thread, but the stop method is very dangerous. It is like turning off the computer power suddenly instead of shutting down according to the normal procedure. It may produce unpredictable results. It is unsafe mainly. : After thread.stop() is called, the thread that created the child thread will throw a ThreadDeatherror error and release all locks held by the child thread.

3. Use interrupt to terminate the thread

When the thread is in two states, use interrpt to terminate

(1) The thread is not in a blocked state:

Use isInterrupted() to determine the interrupt flag of the thread to exit the loop. When using the interrupt() method, the interrupt flag will be set to true, which is the same as using a custom flag to control the loop

public class MyThread extends Thread {
    @Override
    public void run() {
        try {
            for (int i = 0; i < 500000; i++) {
                if (interrupted()) {
                    System.out.println("已经是停止状态了");
                    throw new InterruptedException();//中断异常
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("我在for下面");
        } catch (InterruptedException e) {
            System.out.println("进run方法中的catch了!");
            e.printStackTrace();
        }
 
    }
}

(2) The thread is in a blocked state: if the sleep method, wait of the synchronization lock, receiver, accept and other methods in the socket are used, the interrupt() method of the thread is called

public class ThreadInterrupt extends Thread {  
    public void run()  {  
        try {  
            sleep(50000);  // 延迟50秒  
        }  
        catch (InterruptedException e) {  
            System.out.println(e.getMessage());  
        }  
    }  
    public static void main(String[] args) throws Exception  {  
        Thread thread = new ThreadInterrupt();  
        thread.start();  
        System.out.println("在50秒之内按任意键中断线程!");  
        System.in.read();  
        thread.interrupt();  
        thread.join();  
        System.out.println("线程已经退出!");  
    }

The above is the detailed content of Several ways and example analysis of Java thread termination. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete