继承Thread实现run方法
public static class Test1 extends Thread{
@Override
public void run(){
System.out.println("自定义逻辑");
}
}
// 执行
new Test1().start();
实现Runable接口并重写run方法
public static class Test2 implements Runnable{
@Override
public void run() {
System.out.println("自定义逻辑");
}
}
// 执行
new Thread(new Test2()).start();
lamda表达式写法
new Thread(()->{
System.out.println("自定义逻辑");
}).start();
实现callable接口并重写call方法
public static class testCall implements Callable {
@Override
public Object call() throws Exception {
System.out.println("业务逻辑");
return "";
}
}
// 执行
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Object> futureTask = new FutureTask<>(new testCall());
Thread threadOne = new Thread(futureTask);
threadOne.start();
Object o = futureTask.get();
System.out.println(o.toString());
}
使用线程池管理线程
线程池参数可自行按照需要进行配置
@Configuration
public class TaskExecutePoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(4);
//最大线程数
executor.setMaxPoolSize(16);
//队列容量
executor.setQueueCapacity(10);
//活跃时间
executor.setKeepAliveSeconds(3);
//线程名字前缀
executor.setThreadNamePrefix("TaskExecutePool-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
}
在spring中使用需要在启动类中加入@EnableAsync,然后在所需方法或者类上加入@Async(“taskExecutor”)即可