【发布时间】:2015-05-15 19:22:14
【问题描述】:
我在一个包含我的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 类的实例。代码如下(为了示例,我删除了所有功能)。
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(){} 方法中杀死线程,我将不胜感激(最好不要设置我将在主类中检查的变量,但如果我必须这样做就这样吧)因为我知道,一旦它到达返回语句,它就完成了,不再需要对run()中创建的变量的任何引用。
生成到控制台的输出如下:
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.shutdown();在此之前
标签: java multithreading terminate