java之可回调的固定线程池

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* 线程池
* @author jynine
*
*/
public class ThreadPools {
private ThreadPoolExecutor threadPool;//线程池
private Map<String, Object> objs;
private ThreadPools(){
//初始5 最大5
threadPool = new ThreadPoolExecutor(5, 5, 1,
TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>());
objs =new ConcurrentHashMap<String, Object>();
}
private static ThreadPools instance = new ThreadPools();
/**
* 获取单例对象
* @return
*/
public static ThreadPools getInstance()
{
return instance;
}
/**
* 执行线程
* @param callCallable
* 回调任务
* @param uuid
* 唯一标识
* @throws ExecutionException
* @throws InterruptedException
*/
public void excuteThread(MyCallable callable,String uuid) throws InterruptedException, ExecutionException{
Future<Object> future = threadPool.submit(callable);
Object reObjs = future.get();
objs.put(uuid, reObjs);
}
/**
* 得到线程池返回值
* @param uuid 唯一标识
* @return
* @throws InterruptedException
*/
public Object getReturnObjs(String uuid) throws InterruptedException{
long st = System.currentTimeMillis();
while (true) {
Object temp = objs.get(uuid);
if(temp != null){
objs.remove(uuid);
return temp;
}else{
//15秒超时
if((System.currentTimeMillis() - st) > 15 * 1000){
return null;
}else{
Thread.sleep(1000);
}
}
}
}
/**
* 关闭线程池
* @throws Exception
*/
public void shutDown() throws Exception{
threadPool.shutdown();
}
}



import java.util.concurrent.Callable;

/**
* 回调任务
* @author jynine
*
*/
public class MyCallable implements Callable<Object> {
private int index;

public MyCallable(int index) {
this.index = index;
}

public int getIndex() {
return index;
}

public void setIndex(int index) {
this.index = index;
}

@Override
public Object call() throws Exception {
return "call"+index;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值