[JavaSE Column 87] Thread termination problem, under what circumstances do threads need to be terminated, and how to terminate Java threads?

Author homepage: Designer Xiao Zheng
About the author: 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, committed to enterprise digital transformation, CSDN Academy, Blue Bridge Cloud Course certified instructor.
Main direction: Vue, SpringBoot, WeChat applet

This article explains the concept of thread termination in Java, explains how to terminate a Java thread, and gives sample code. Thread termination refers to the process in which the execution of a thread ends or is interrupted. Thread safety and resources need to be considered when terminating a thread. Regarding release issues, threads should be cleaned up and closed at the appropriate time to avoid resource leaks and data consistency issues.

Directory

  • 1. What is thread termination?
  • 2. Under what circumstances does the thread need to be terminated?
  • 3. Thread termination simulation
  • 4. Application scenarios of thread termination
  • 5. Thread termination interview questions
  • 6. Summary

1. What is thread termination

Thread termination refers to the process in which the execution of a thread ends or is interrupted.

Thread termination can be done by

5

5

Triggered by 5 situations, please study carefully.

  1. The thread execution is completed. When the thread finishes executing all the code, the thread will automatically terminate.
  2. By calling the thread’s stop() method, in Java, the stop() method is deprecated and is not recommended. Because it will cause the thread to terminate suddenly, which may lead to unpredictable results.
  3. By calling the thread’s interrupt() method, the interrupt() method will send an interrupt signal to the thread, but it will not directly terminate the thread. A thread can decide whether to terminate execution by checking the interrupt flag bit.
  4. To terminate a thread by setting its flag bit, you can use a volatile type flag bit to control the execution of the thread. When the flag bit is set to the termination state, the thread can Exit execution safely.
  5. Throws an uncaught exception. When an uncaught exception is thrown in a thread, the thread will terminate execution. In this case, you can catch the exception and handle it, or perform global exception handling in the uncaughtException() method of the Thread class.

Thread termination does not occur immediately, but requires waiting for the code block or method executed by the thread to end before it terminates. Therefore, when writing multi-threaded code, students need to pay attention to the thread termination conditions and the safe exit of the thread.

2. Under what circumstances does a thread need to be terminated

In the following

5

5

In 5 situations, students may need to terminate the Java thread to ensure the data accuracy of the Java project.

  1. Task Completion: When the thread’s task has been completed and no longer needs to be executed, you can choose to terminate the thread. For example, a download thread can terminate after all files have been downloaded.
  2. External interrupt: When other threads or external events occur, the execution of a thread needs to be interrupted. This is accomplished by calling the thread’s interrupt() method. The interrupted thread needs to check the interrupt flag bit and terminate the thread’s execution as necessary.
  3. Resource release: The thread may allocate some resources during execution, such as open files, network connections, or database connections. After the thread completes execution, these resources need to be released and the thread terminated.
  4. Error handling: When a thread encounters an error or exception that cannot be handled, it may be necessary to terminate the execution of the thread. For example, a fatal error occurs while processing a certain task and cannot be recovered. In this case, you can choose to terminate the thread. .
  5. Application shutdown: When an application needs to be shut down, it is usually necessary to terminate all executing threads. This can be done by setting a global exit flag and letting the threads check the flag and exit safely.

Thread safety and resource release issues need to be considered when terminating threads. Threads should be cleaned up and closed at the appropriate time to avoid resource leaks and data consistency issues.

3. Thread termination simulation

In order to let students better understand thread termination, I wrote a piece of code that simulates thread termination. Students can copy it to local execution and check whether the execution results are as expected.

public class ThreadTerminationDemo {<!-- -->
    public static void main(String[] args) {<!-- -->
        WorkerThread workerThread = new WorkerThread();
        workerThread.start(); // Start the worker thread

        try {<!-- -->
            Thread.sleep(5000); //The main thread sleeps for 5 seconds
        } catch (InterruptedException e) {<!-- -->
            e.printStackTrace();
        }

        workerThread.terminate(); // Terminate the worker thread
    }
}

class WorkerThread extends Thread {<!-- -->
    private volatile boolean isTerminated = false;

    @Override
    public void run() {<!-- -->
        // Simulate thread execution tasks
        while (!isTerminated) {<!-- -->
            System.out.println("Working...");
            try {<!-- -->
                Thread.sleep(1000);
            } catch (InterruptedException e) {<!-- -->
                e.printStackTrace();
            }
        }
        System.out.println("Worker thread terminated.");
    }

    public void terminate() {<!-- -->
        isTerminated = true;
    }
}

In the sample code above, the main thread starts a worker thread WorkerThread.

The worker thread will continue to execute tasks in the loop until the isTerminated flag is set to

t

r

u

e

true

Terminate when true.

The main thread is sleeping

5

5

Call the workerThread.terminate() method after 5 seconds to terminate the worker thread.

The worker thread detects that isTerminated is

t

r

u

e

true

When true, exit the loop, perform cleanup work and print termination information.

Among them, I used the volatile modifier in the code to ensure the visibility of the isTerminated variable and ensure that the worker thread can correctly read the status of the termination flag.

4. Application scenarios of thread termination

  1. Background task completion: When a thread completes a background task, the thread can be terminated. For example, in a file downloader, when all files have been downloaded, the download thread can be terminated.
  2. Resource release: The thread may allocate some resources during execution, such as open files, network connections, or database connections. After the thread completes its task, these resources need to be released and the thread terminated.
  3. Timeout processing: Sometimes it is necessary to set the execution time of a thread. If the thread does not complete the task within the specified time, the thread can be terminated. For example, in a network request, if the request times out, the thread can be terminated. thread.
  4. Error handling: When a thread encounters an error or exception that cannot be handled, the execution of the thread may need to be terminated. For example, in an image processing thread, if an image format that cannot be processed is encountered, the thread can be terminated.
  5. Application shutdown: When an application needs to be shut down, it is usually necessary to terminate all executing threads. This can be done by setting a global exit flag and letting the threads check the flag and exit safely.

Thread termination needs to be handled with caution. Ensure that the thread terminates at the appropriate time and performs necessary resource cleanup and shutdown. At the same time, the thread termination method should match the thread’s design and task requirements to avoid resource problems. Leakage or data inconsistency issues.

5. Thread termination interview questions

Question: How to gracefully terminate a running Java thread?

  1. Use flag bits: During the execution of a thread’s task, the execution status of the thread is controlled by setting a flag bit. When the thread executes the task, it constantly checks the status of the flag bit. When the flag bit is set to

    t

    r

    u

    e

    true

    When true, the thread exits execution on its own, so that after the task execution is completed, the flag bit can be set to

    t

    r

    u

    e

    true

    true to terminate the thread.

  2. Use the interrupt() method: You can interrupt the execution of a thread by calling the thread’s interrupt() method. The interrupted thread needs to check the interrupt flag bit and terminate the execution of the thread as needed. Usually when an InterruptedException exception is caught, the thread can choose to terminate execution.
  3. Use the stop() method: Try to avoid using the stop() method to terminate the thread, because it may cause the thread to be unable to release resources and clean up the state normally, causing a series of problems , it is recommended to use other ways to terminate threads gracefully.

When a thread terminates, thread safety and resource release issues need to be considered. The thread should be cleaned up and closed at the appropriate time to avoid resource leaks and data consistency issues. The thread termination method should be consistent with the thread’s design and task requirements. Match to ensure the correctness and reliability of the termination operation.

6. Summary

This article explains the concept of thread termination in Java, explains how to terminate a Java thread, and gives sample code. In the next blog, we will explain how Java implements the conversion of objects and JSON strings.