Spring 通过多种方式实现使用线程
示例:Spring 中实现 Runnable
import org.springframework.stereotype.Component;
@Component
public class MyRunnable implements Runnable {
@Override
public void run() {
// 在这里定义线程要执行的任务
System.out.println("线程正在运行: " + Thread.currentThread().getName());
try {
Thread.sleep(1000); // 模拟任务执行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程执行完成: " + Thread.currentThread().getName());
}
}
在 Spring 中启动线程
方法 1:直接启动线程
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
@Autowired
private MyRunnable myRunnable;
public void startTask() {
// 启动线程
Thread thread = new Thread(myRunnable);
thread.start();
}
}
方法 2:使用 Spring 的 TaskExecutor
Spring 提供了 TaskExecutor
接口,用于更灵活地管理线程池。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.core.task.TaskExecutor;
@Service
public class TaskService {
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private MyRunnable myRunnable;
public void startTask() {
// 使用 TaskExecutor 启动线程
taskExecutor.execute(myRunnable);
}
}
配置线程池(可选)
如果你使用 TaskExecutor
,可以在 Spring 配置类中定义一个线程池:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class ThreadPoolConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // 核心线程数
executor.setMaxPoolSize(10); // 最大线程数
executor.setQueueCapacity(25); // 队列容量
executor.setThreadNamePrefix("MyThread-"); // 线程名称前缀
executor.initialize();
return executor;
}
}
测试代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private TaskService taskService;
@Override
public void run(String... args) throws Exception {
// 启动任务
taskService.startTask();
}
}
运行结果
当你运行 Spring Boot 应用程序时,控制台会输出类似以下内容:
线程正在运行: MyThread-1
线程执行完成: MyThread-1
总结
-
实现
Runnable
接口:定义线程的任务逻辑。 -
启动线程:可以通过
new Thread()
或 Spring 的TaskExecutor
启动线程。 -
线程池配置:使用
ThreadPoolTaskExecutor
配置线程池,提高线程管理的灵活性。