How to kill a java thread?

前端 未结 8 1957
一个人的身影
一个人的身影 2020-12-11 08:26

I google the solution for killing a java thread. And there exists two solutions:

  1. set a flag
  2. using Thread.interrupt

But both of them ar

相关标签:
8条回答
  • 2020-12-11 09:14

    Since Thread.stop() is (rightly) deprecated, generally this is accomplished by setting a flag to true. Something like this:

    Calling Class:

    ...
    workListExecutor.stop()
    ...
    

    WorkListExecutor.class:

    boolean running = true;
    
    void stop(){
      running = false;
    }
    
    void run(){
      while (running) {
        ... do my stuff ...
      }
    }
    

    This is assuming your thread has some kind of main loop (usually the case). If the code in your loop is too big, you can periodically check if running is still true, and bail out if it's not.

    This has the advantage that you can still clean up when you're done. The thread will be killed automatically when your run method finishes.

    0 讨论(0)
  • 2020-12-11 09:18

    I would put the call a third-party api which takes a long time into a Callable<DataTypeReturnedBy3rdPartAPI> and then execute it with a SingleThreadExecutor specifying a timeout.

    Following this approach, the thread will be killed if the call to third party API takes longer than timeOut, here is some code to exemplify what I am saying:

    ExecutorService executor = Executors.newSingleThreadExecutor();
     try {
       //================= HERE ==================
       Future<Boolean> job = executor.submit(thirdPartyCallable);
       executor.awaitTermination(timeOut, TimeUnit.SECONDS);      
       if(!job.isDone())
         logger.debug("Long call to 3rd party API didn't finish");
       //=========================================
     } catch (Exception exc) {
         exc.printStackTrace();      
     } finally {
         if(!executor.isShutdown() )
           executor.shutdownNow();
     }
    
    }  
    
    private static Callable<Boolean>  thirdParytCallable = new Callable<Boolean>() {
      public Boolean call() throws Exception {
        //Call to long 3rd party API
        //.......
        for(long i = 0;i<99999991999999L;i++) {
          Thread.sleep(10L);// Emulates long call to 3rd party API
          System.out.print(".");
        }
        return Boolean.valueOf(true);//Data from 3rd party API
      }
    }; 
    
    0 讨论(0)
提交回复
热议问题