Java创建线程的方式 & SpringBoot优雅使用线程池

目录

1、继承Thread类

2、实现Runnable接口

3、实现Callable接口(通过Callable和Future创建线程,有返回值)

4、SpringBoot优雅使用线程池


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("需要执行的代码"));

书到用时方恨少,事非经过不知难

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值