`

java之可回调的固定线程池

    博客分类:
  • 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;
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics