在我的Spring應用程序中,我啓動了一個像這樣的線程。在春天停止線程
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;
@Component
public class RunBackgroundServices implements ApplicationListener<ContextRefreshedEvent> {
private final BackgroundServices backgroundServices;
private ExecutorService executor;
@Autowired
public RunBackgroundServices(BackgroundServices backgroundServices) {
this.backgroundServices= backgroundServices;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
executor = Executors.newSingleThreadExecutor();
executor.submit(backgroundServices);
}
public void onApplicationEvent(ContextStoppedEvent event) {
backgroundServices.close();
executor.shutdownNow();
}
}
這是線程BackGroundServices。
public class BackgroundServices extends Thread {
@Autowired
HL7Listener hL7Listener;
@Autowired
HISListener hISListener;
@Autowired
PollHIS pollHIS;
@Autowired
PollPatientPortal pollPatientPortal;
private static final Logger logger = LoggerFactory.getLogger(BackgroundServices.class);
public void run() {
logger.debug("BackgroundServices :: run");
try {
hL7Listener.start();
} catch (InterruptedException e) {
logger.error(e.getStackTrace().toString());
}
try {
hISListener.start();
} catch (InterruptedException e) {
logger.error(e.getStackTrace().toString());
}
while (true) {
pollHIS.start();
pollPatientPortal.start();
}
}
public void close(){
hL7Listener.stop();
hISListener.stop();
}
}
但是當我停止服務器時,線程繼續在後臺運行。我無法控制執行者,是否有辦法阻止該線程?