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

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值