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;
}
}