我需要创建一个监听DatagramSocket
的专用线程。
过去的做法是在上下文创建过程中创建一个:
@Bean
void beanDef() {
var thread = new Thread(myRunnable);
thread.setDaemon(true);
thread.start();
}
更现代的方法是创建执行程序:
@Bean
Executor() {
var executor = Executors.newSingleThreadExecutor();
executor.submit(myRunnable);
}
我应该选哪个?
答案 0 :(得分:1)
像这样的事情将是在Spring中启动后台线程的一种现代方式:
@Component
public class MySocketListenerLauncher {
private ExecutorService executorService;
@PostConstruct
public void init() {
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("socket-listener-%d").build();
executorService = Executors.newSingleThreadExecutor(factory);
executorService.execute(new Runnable() {
@Override
public void run() {
// ... listen to socket ...
}
});
executorService.shutdown();
}
@PreDestroy
public void shutdown() {
if (executorService != null) {
executorService.shutdownNow();
}
}
}
答案 1 :(得分:0)
最好使用@Async
批注在后台创建线程。
@EnableAsync
注释打开了Spring在后台线程池中运行@Async
方法的功能。此类还自定义使用的Executor。
@Configuration
@EnableAsync
public class ThreadConfig {
@Bean(name = "specificTaskExecutor")
public TaskExecutor specificTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.initialize();
return executor;
}
}
以及以下代码段
@Async("specificTaskExecutor")
public void runFromAnotherThreadPool() {
System.out.println("You function code here");
}
我希望这会对您有所帮助。