这是我的应用类 -
@EnableAutoConfiguration
@SpringBootApplication
@Configuration
public class Application implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(Application.class);
@Autowired
private ITestService3 testService3;
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(Application.class, args)));
@Override
public void run(String... strings) throws Exception {
testService3.multiThreadTest();
}
}
方法 -
public void multiThreadTest() {
ThreadPoolExecutor readExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
List<String> files = listFiles(new File("/Users/admin/filesList"), new ArrayList<>());
for (String file : files) {
readExecutor.execute(new FileParser(file));
}
}
即使在读取所有文件后,应用程序也不会终止 但是当我使用
时System.exit(SpringApplication.exit(SpringApplication.run(Application.class,args)));
应用程序终止,所有线程都被终止。
当我使用 -
SpringApplication.run(Application.class,args).close();
即使应用程序说明了这一点,线程仍然继续运行 -
org.springframework.context.annotation.AnnotationConfigApplicationContext@6eda5c9:启动日期[Mon Aug 15 04:42:02 IST 2016];上下文层次结构的根 2016-08-15 04:42:05.390 INFO 36600 --- [main] o.s.j.e.a.AnnotationMBeanExporter:在关机时取消注册JMX暴露的bean
然后我必须手动杀死该应用程序。应用程序退出代码130
有人可以帮我找一个优雅地关闭应用程序的方法。
由于
答案 0 :(得分:0)
首先,您没有正确关闭ExecutorService
,multiThreadTest
应如下:
public void multiThreadTest() throws InterruptedException {
ThreadPoolExecutor readExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
List<String> files = listFiles(new File("/Users/admin/filesList"), new ArrayList<>());
for (String file : files) {
readExecutor.execute(new FileParser(file));
}
readExecutor.shutdown();
readExecutor.awaitTermination(5, TimeUnit.MINUTES); // wait for tasks to complete
readExecutor.shutdownNow();
}