Java 借助线程池创建并发线程
发布时间:2021-11-25 21:06:56 所属栏目:教程 来源:互联网
导读:import Java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExecutorUtil { // 池中所保存的线程数,包括空闲线程 private static final int corePo
import Java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExecutorUtil { // 池中所保存的线程数,包括空闲线程 private static final int corePoolSize = 10; // 池中允许的最大线程数 private static final int maximumPoolSize = 100; // 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间(目前设为1800秒即30分钟) private static final int keepAliveTime = 1800; // 执行前用于保持任务的队列 private static final int blockingQueueSize = 10; // 参数的时间单位 private static final TimeUnit unit = TimeUnit.SECONDS; private static ThreadPoolExecutor threadPool = null; /** * 获取线程池的单例 * @return */ public static ThreadPoolExecutor getPoolInstance() { if (threadPool == null) { synchronized (ThreadPoolExecutor.class) { // 实例化线程池 threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, new ArrayBlockingQueue<Runnable>(blockingQueueSize), new ThreadPoolExecutor.DiscardOldestPolicy()); } } // 返程线程池的实例化对象 return threadPool; } public static void main(String[] args) { for (int i = 0; i < 10; i++) { // 实例化线程池 ThreadPoolExecutor threadPool = ThreadPoolExecutorUtil .getPoolInstance(); // 触发并行线程的运行 threadPool.execute(new SingleThread(i+"")); } } } class SingleThread implements Runnable { private String name = null; public SingleThread(String name) { this.name = name; } public void run() { System.out.println("parallel run..." + name); } } ![]() (编辑:江门站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |