在这个类中,包含了ThreadPoolExector和ScheduledThreadPoolExecutor,前者是利用线程池执行任务的类,后者是利用线程池定时执行任务的类。
//package com.fourinone;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
class PoolExector //java.io.Closeable
{
private static ThreadPoolExecutor tpe;
private static ScheduledThreadPoolExecutor stpe;
//使用可用的几个池线程之一来执行任务
static ThreadPoolExecutor tpe()
{
if(tpe==null)
{
int corePoolSize = ConfigContext.getInitServices();
int maximumPoolSize = ConfigContext.getMaxServices();
long keepAliveTime = 3000;
TimeUnit unit = TimeUnit.MILLISECONDS;
BlockingQueue waitQueue = new ArrayBlockingQueue(2000);
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();//ThreadPoolExecutor.CallerRunsPolicy();
/**
*corePoolSize:核心线程数
*maximumPoolSize:最大线程数
*keepAliveTime:当线程数大于corePoolSize时,终止多余的线程所等待的时间
*unit:keepAliveTime的单位
*waitQueue:要执行的任务队列
*handler:线程被阻塞时使用的处理程序
*/
tpe =new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, waitQueue, handler);
}
return tpe;
}
static ScheduledThreadPoolExecutor stpe()
{
if(stpe==null)
{
int corePoolSize = ConfigContext.getInitServices();
stpe =new ScheduledThreadPoolExecutor(corePoolSize);
}
return stpe;
}
static void execute(Runnable d, Runnable i, long t){
tpe().execute(d);
if(t>0)
stpe().schedule(i,t,TimeUnit.SECONDS);//在t秒之后执行任务i
}
static void close(){
if(tpe!=null){
try{
tpe.shutdown();
tpe=null;
}catch(SecurityException se){
LogUtil.info("[tpe]", "[close]", "[Error Exception:]", se);
}
}
if(stpe!=null){
try{
stpe.shutdown();
stpe=null;
}catch(SecurityException se){
LogUtil.info("[stpe]", "[close]", "[Error Exception:]", se);
}
}
}
}
测试代码:
import javax.xml.parsers.*;
import java.util.*;
import org.xml.sax.*;
import java.io.*;
import java.util.concurrent.*;
public class Demo
{
public static void main(String[] args) throws Exception
{
PoolExector.tpe();
PoolExector.stpe();
PoolExector.execute(new A(),new B(),5);
PoolExector.close();
}
}
class A implements Runnable
{
public void run()
{
try
{
int temp=0;
while(temp++<20)
{
System.out.println("A:"+Thread.currentThread().getName()+"正在执行");
TimeUnit.SECONDS.sleep(1);
}
}
catch (InterruptedException e){}
}
}
class B implements Runnable
{
public void run()
{
try
{
int temp=0;
while(temp++<10)
{
System.out.println("B:"+Thread.currentThread().getName()+"正在执行");
TimeUnit.SECONDS.sleep(2);
}
}
catch (InterruptedException e){}
}
}