Runnable
Thread thread = new Thread(()->{});
thread.start();
CompletableFuture
runAsync:没有返回值
supplyAsync:有返回值,通过get()方法获取返回值(会阻塞)
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("无返回值...");
});
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("有返回值...");
return "Hello World";
});
String result = future.get();
System.out.println(result);
ThreadPoolExecutor
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors() * 2, 16,
5L, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(30),
new ThreadPoolExecutor.CallerRunsPolicy()
);
threadPool.submit(() -> {
});
Async注解
@Service
public class ThreadService {
@Async("taskExecutor")
public void run() {
}
}
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean("taskExecutor")
public Executor pool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("asyncServiceExecutor :");
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}