How to stop a thread?

前端 未结 4 1774
逝去的感伤
逝去的感伤 2020-11-27 08:15

When a thread is alive, how can I stop the thread? I have given like

if(thread.isAlive()){
    thread.stop();
}

but the method stop is depr

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 08:43

    In general, you don't forcibly stop threads because it's dangerous. You set a flag that tells the thread in question to exit from it's thread loop under controlled circumstances.

    Your thread loop looks something along these lines:

    void run() {
      while (shouldContinue) {
        doThreadWorkUnit();
      }
    }
    

    And somewhere else you set the shouldContinue variable and wait for the thread to finish:

    ...
    thread.shouldContinue = false;
    thread.join();
    ...
    

    (All this is likely not correct Java, since I don't do Java. View it as pseudo code and modify for your actual language/thread library/etc.)

提交回复
热议问题