示例:Spring 中实现 Runnable
import org.springframework.stereotype.Component;@Component
public class MyRunnable implements Runnable {@Overridepublic 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 {@Autowiredprivate 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 {@Autowiredprivate TaskExecutor taskExecutor;@Autowiredprivate 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 {@Beanpublic 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 {@Autowiredprivate TaskService taskService;@Overridepublic void run(String... args) throws Exception {// 启动任务taskService.startTask();}
}
运行结果
当你运行 Spring Boot 应用程序时,控制台会输出类似以下内容:
线程正在运行: MyThread-1
线程执行完成: MyThread-1
总结
-
实现
Runnable
接口:定义线程的任务逻辑。 -
启动线程:可以通过
new Thread()
或 Spring 的TaskExecutor
启动线程。 -
线程池配置:使用
ThreadPoolTaskExecutor
配置线程池,提高线程管理的灵活性。