java多线程(线程池)

发布时间:2024年01月18日

1、创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

public static void main(String[] args) {
 
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            cachedThreadPool.execute(() -> {
                System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
            });
        }
    }

2、创建一个固定线程数量,可重用的线程池。

public static void main(String[] args) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            fixedThreadPool.execute(() -> {
                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
            });
        }
    }

3、创建一个指定最多线程数量的线程池。

package com.controller;

import com.myThread.AdminThread;
import com.myThread.MyCallable;
import com.myThread.MyRunnable;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.*;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController{
    @GetMapping("/{id}")
    public long findById(@PathVariable Long id) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
        System.out.println(pool.getPoolSize());//0
        for (int i = 0; i < 10; i++) {
            executorService.submit(()->{
                System.out.println(Thread.currentThread().getName() + "在执行了");
            });
        }
        return id;
    }
}

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_34631220/article/details/135684195
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。