Java - 关闭线程 'return' 不工作

Java - Close a thread with 'return' not working

我在 class 中有以下代码,其中包含我的 main 方法

ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable formatConcentration = new formatConcentration(87);
executor.execute(formatConcentration);
System.out.println("Called an instance of formatConcentration");
while (!executor.isTerminated())
{
    //stay Alive
    Thread.sleep(1000);
    System.out.println("Still alive");
}
System.out.println("Program successfully finished");
return;

这将创建 formatConcentration class 的实例。其代码如下(为了示例,我已经删除了所有功能)。

public class formatConcentration extends Thread{
    private int numberOfNewRows;

    formatConcentration(int rows)
    {
        this.numberOfNewRows = rows;
    }
    public void run() {

        System.out.println("Running the Formatting Script");
        final int numberOfNewRegistered = this.numberOfNewRows;
        try 
        {
            System.out.println("Finished formatting");
        }//end of try
        catch (Exception e1) 
        {
            log.log(e1.toString());
            log.closeLog() ;
            System.exit(1) ;
        }
        System.out.println("Still Finished formatting");
        return;
    }
}

我的问题是,一旦 return 被调用,它就不会终止线程。

我已经做了很多环顾四周的工作,据我所知这应该没问题,但我想我忽略了一些小事,希望对这个问题有新的看法。

或者如果有人建议如何从 run(){} 方法中终止线程,我将不胜感激(最好不要通过设置一个我将在主 [=32= 中检查的变量) ] 但如果我必须这样做,那就这样吧)因为我知道一旦它到达 return 语句它就完成了并且不再需要任何对在 run().[=20= 中创建的变量的引用]

生成到控制台的输出如下:

Called an instance of formatConcentration
Running the Formatting Script
Finished formatting
Still Finished formatting
Still alive
Still alive
Still alive
Still alive
Still alive
etc.

您从未关闭 executor。来自 isTerminated:

的 Javadocs

Returns true if all tasks have completed following shut down. Note that isTerminated is never true unless either shutdown or shutdownNow was called first.

只要不关闭executor,就可以提交新的任务给它执行。 isTerminated 检查提交任务的状态,它检查 ExecutorService 本身的状态。

ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable formatConcentration = new formatConcentration(87);
executor.execute(formatConcentration);
System.out.println("Called an instance of formatConcentration");
executor.shutdown();
while (!executor.isTerminated())
{
    //stay Alive
    Thread.sleep(1000);
    System.out.println("Still alive");
}
System.out.println("Program successfully finished");
return;

另一种更简单的方法是:

   ExecutorService executor = Executors.newFixedThreadPool(1);
    Runnable formatConcentration = new formatConcentration(87);
    executor.execute(formatConcentration);
    executor.shutdown();
    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

执行器 awaitTermination 方法替代您的循环。

ExecutorService主要用于将你的工作委托给separte worker。 使用它只创建了大部分连接池库。 所以这个服务会在你的应用程序启动的时候启动,并且会通过你的应用程序的关闭方法关闭(手动)。

在您的程序中,您应该编写代码来检查执行程序服务的状态,

目前有工人在工作吗... 如果没有工作人员处于忙碌模式,则停止接受任何进一步的任务。

从 javadocs 查看示例关闭代码,

以下方法分两个阶段关闭 ExecutorService,首先通过调用 shutdown 拒绝传入任务,然后调用 shutdownNow(如有必要)取消任何延迟任务:

void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

希望能给大家一些信息。