Is there a good way to forcefully stop a Java thread?

后端 未结 5 1264
清歌不尽
清歌不尽 2020-12-03 11:40

I want to stop a Java thread immediately but when I try the thread always takes some time before stopping. Is there a good way to force a Java thread to stop instantly?

5条回答
  •  心在旅途
    2020-12-03 11:55

    Running Thread cannot be stopped using Thread.Interrupt , only waiting or blocking threads can be stopped using Thread.Interrupt.But using a shared variable to signal that it should stop what it is doing. The thread should check the variable periodically,(ex : use a while loop ) and exit in an orderly manner.

    private boolean isExit= false;
    
    public void beforeExit() {
        isExit= true;
    }
    
    public void run() {
        while (!isExit) {
    
        }
    }
    

提交回复
热议问题