终止Java线程无异常

时间:2018-03-13 13:39:50

标签: java multithreading sorting javafx

我有一个Java程序,我需要杀死一个线程。 它不需要被优雅地杀死,我只需要线程结束,因为我在窗口关闭时调用它来杀死一堆线程作为JavaFX的动作处理程序。

以下是相关计划:https://github.com/Aashishkebab/Sorting-Simulator

基本上,程序实现了一堆排序算法,允许用户选择一个,然后选择一个块大小。 程序将排序拆分为用户输入大小的块,然后在不同的线程上同时对所有这些块进行排序。

但是,关闭窗口会导致线程在后台继续排序。我需要能够使所有这些操作在关闭窗口时停止(或者按下kill按钮或任何情况)。

我并不担心数据的安全性,或者是否出现空指针等等。我只是希望程序真正退出。

4 个答案:

答案 0 :(得分:4)

只需创建线程守护程序线程即可。守护程序线程不会阻止JVM退出。这可以像

一样简单
Runnable mySortAlgorithm = ... ;
Thread thread = new Thread(mySortAlgorithm);
thread.setDaemon(true);
thread.start();

如果您使用执行程序来管理您的主题,即您有

Executor exec = ... ;
//...

Runnable mySortAlgorithm = ... ;
exec.execute(mySortAlgorithm);

您可以创建一个创建守护程序线程的执行程序,例如

Executor exec = Executors.newCachedThreadPool(runnable -> {
    Thread t = new Thread(runnable);
    t.setDaemon(true);
    return t ;
});

//...

Runnable mySortAlgorithm = ... ;
exec.execute(mySortAlgorithm);

答案 1 :(得分:2)

如果您使用Executors创建ExecutorServicesubmit() Callable任务,那么可以使用myExecutorService.shutdownNow()

如果您想要更好地控制线程,请查看CompletableFuture.supplyAsync()

答案 2 :(得分:0)

System.exit(myExitCode);怎么样。

但更清晰的解决方案是使您的排序算法可以取消。例如,请参阅here

同样有用的是this

答案 3 :(得分:-1)

直接杀死线程不安全。

推荐的方法是使用一个标志,该标志可以通知线程是时候停止。

如果您可以访问和修改代码,可以在线程类中创建一个名为stop()的方法,这样当您需要终止进程时,可以调用myClass.stop()。

例如:

public class myClass{

  private boolean keepAlive = true;

  public void run(){

     keepAlive = true;
     while(keepAlive){
       //do work
     }
  }

  public void stop(){
    keepAlive = false;
  }
}