Java 利用线程池创建并发线程

  • A+
所属分类:Linux编程
摘要

// 池中允许的最大线程数private static final int maximumPoolSize = 100;// 当线程数大于核心时,此为终止前多余的空闲线程等

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

 }

除非注明,否则均为@蒲公英网原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.aipgy.com/51938.html

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: