手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2011-07-05] 来源:Linux社区  作者:Linux [字体:大 中 小]

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

 }

 

}

linux
相关资讯       Java 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款