SoFunction
Updated on 2025-05-19

How to use threads in Spring in many ways

Example: Implementing Runnable in Spring

import ;

@Component
public class MyRunnable implements Runnable {

    @Override
    public void run() {
        // Define the tasks to be executed by the thread here        ("Thread is running: " + ().getName());
        try {
            (1000); // Simulate task execution        } catch (InterruptedException e) {
            ();
        }
        ("Thread execution is completed: " + ().getName());
    }
}

Start a thread in Spring

Method 1: Start the thread directly

import ;
import ;

@Service
public class TaskService {

    @Autowired
    private MyRunnable myRunnable;

    public void startTask() {
        // Start the thread        Thread thread = new Thread(myRunnable);
        ();
    }
}

Method 2: Use Spring's TaskExecutor

Spring providesTaskExecutorInterface for more flexible management of thread pools.

import ;
import ;
import ;

@Service
public class TaskService {

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private MyRunnable myRunnable;

    public void startTask() {
        // Use TaskExecutor to start the thread        (myRunnable);
    }
}

Configure thread pool (optional)

If you useTaskExecutor, you can define a thread pool in the Spring configuration class:

import ;
import ;
import ;

import ;

@Configuration
public class ThreadPoolConfig {

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        (5); // Number of core threads        (10); // Maximum number of threads        (25); // Queue capacity        ("MyThread-"); // Thread name prefix        ();
        return executor;
    }
}

Test code

import ;
import ;
import ;

@Component
public class AppRunner implements CommandLineRunner {

    @Autowired
    private TaskService taskService;

    @Override
    public void run(String... args) throws Exception {
        // Start the task        ();
    }
}

Running results

When you run a Spring Boot application, the console outputs something like the following:

Thread is running: MyThread-1
Thread execution completed: MyThread-1

Summarize

  • accomplishRunnable interface: Define the task logic of the thread.
  • Start the thread: Can be passednew Thread()Or Spring'sTaskExecutorStart the thread.
  • Thread pool configuration:useThreadPoolTaskExecutorConfigure thread pools to improve thread management flexibility.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.