Created
May 28, 2024 06:05
-
-
Save wbminsssss/aa03ed97461f7869e8ef65068de9483e to your computer and use it in GitHub Desktop.
创建一个虚拟线程池
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.concurrent.BlockingQueue; | |
| import java.util.concurrent.ExecutorService; | |
| import java.util.concurrent.LinkedBlockingQueue; | |
| import java.util.concurrent.ThreadFactory; | |
| import java.util.concurrent.ThreadPoolExecutor; | |
| import java.util.concurrent.TimeUnit; | |
| /** | |
| * @author wubo | |
| */ | |
| public class VirtualThreadPool { | |
| private static volatile ExecutorService executor; | |
| private VirtualThreadPool() {} | |
| public static ExecutorService getExecutor() { | |
| if (executor == null) { | |
| synchronized (VirtualThreadPool.class) { | |
| if (executor == null) { | |
| // 根据实际需求配置线程池参数 | |
| int corePoolSize = 3; | |
| int maximumPoolSize = corePoolSize * 2; | |
| long keepAliveTime = 60L; | |
| TimeUnit unit = TimeUnit.SECONDS; | |
| BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100); | |
| ThreadFactory factory = Thread.ofVirtual().factory(); | |
| executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory); | |
| } | |
| } | |
| } | |
| return executor; | |
| } | |
| public static void shutdown() { | |
| if (executor != null) { | |
| executor.shutdown(); | |
| try { | |
| if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { | |
| executor.shutdownNow(); | |
| if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { | |
| System.err.println("线程池无法终止"); | |
| } | |
| } | |
| } catch (InterruptedException ie) { | |
| executor.shutdownNow(); | |
| Thread.currentThread().interrupt(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment