java之可回调的固定线程池_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java之可回调的固定线程池

java之可回调的固定线程池

 2013/12/10 22:09:07  jynine  程序员俱乐部  我要评论(0)
  • 摘要:importjava.util.Map;importjava.util.concurrent.ConcurrentHashMap;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.Future;importjava.util.concurrent.LinkedBlockingQueue;importjava.util.concurrent.ThreadPoolExecutor;importjava
  • 标签:Java 线程
class="java" name="code">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;
	}

}
上一篇: IOS沙盒Files目录说明和常用操作 下一篇: 没有下一篇了!
发表评论
用户名: 匿名