目录
3、实现Callable接口(通过Callable和Future创建线程,有返回值)
1、继承Thread类
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.println("需要执行的代码");
}
};
thread.start();
}
2、实现Runnable接口
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("需要执行的代码");
}
};
Thread thread = new Thread(runnable);
thread.start();
}
3、实现Callable接口(通过Callable和Future创建线程,有返回值)
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Map<String, Object>> task = new FutureTask<Map<String, Object>>(new Callable() {
@Override
public Object call() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("result", "success");
return map;
}
});
Thread thread = new Thread(task);
thread.start();
Map<String, Object> map = task.get();
System.out.println(map);
}
4、SpringBoot优雅使用线程池
使用guava的ThreadFactoryBuilder来创建线程池
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
application.yml配置线程池参数
# 线程池参数
threadPool:
corePoolSize: 5
maximumPoolSize: 10
queueCapacity: 5
线程池配置类
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author zyykin
*/
@Configuration
public class ThreadPoolConfig {
@Value("${threadPool.corePoolSize}")
private int corePoolSize;
@Value("${threadPool.maximumPoolSize}")
private int maximumPoolSize;
@Value("${threadPool.queueCapacity}")
private int queueCapacity;
/**
* 线程池
*
* @return ThreadPool
*/
@Bean(value = "threadPool")
public ExecutorService buildThreadPool() {
return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(queueCapacity),
new ThreadFactoryBuilder().setNameFormat("demo-thread-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
}
}
使用伪代码
@Resource(name = "threadPool")
private ExecutorService threadPool;
threadPool.execute(() -> System.out.println("需要执行的代码"));
书到用时方恨少,事非经过不知难