How to properly stop the Thread in Java?

后端 未结 9 1171
执念已碎
执念已碎 2020-11-21 16:19

I need a solution to properly stop the thread in Java.

I have IndexProcessorclass which implements the Runnable interface:

public class          


        
9条回答
  •  误落风尘
    2020-11-21 16:28

    Simple answer: You can stop a thread INTERNALLY in one of two common ways:

    • The run method hits a return subroutine.
    • Run method finishes, and returns implicitly.

    You can also stop threads EXTERNALLY:

    • Call system.exit (this kills your entire process)
    • Call the thread object's interrupt() method *
    • See if the thread has an implemented method that sounds like it would work (like kill() or stop())

    *: The expectation is that this is supposed to stop a thread. However, what the thread actually does when this happens is entirely up to what the developer wrote when they created the thread implementation.

    A common pattern you see with run method implementations is a while(boolean){}, where the boolean is typically something named isRunning, it's a member variable of its thread class, it's volatile, and typically accessible by other threads by a setter method of sorts, e.g. kill() { isRunnable=false; }. These subroutines are nice because they allow the thread to release any resources it holds before terminating.

提交回复
热议问题