import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步任务总控制器
*
* @author shenl
*
*/
public class AsynchronousService {
private static ExecutorCompletionService<Callable<?>> ecs = null;
private static ExecutorService pool = null;
static {
pool = Executors.newFixedThreadPool(70);
ecs = new ExecutorCompletionService<Callable<?>>(pool);
}
/**
* 提交一个异步任务
*
* @param thread
* @return
*/
public static Object submit(CcstudyCallable thread) {
// 默认超时为5分钟
return submit(thread, 5 * 60 * 1000);
}
public static Object submit(CcstudyCallable thread, long timeout) {
Future<?> futureTask = ecs.submit(thread);
return futureTask;
}
public static Object take() throws InterruptedException {
return ecs.take();
}
/**
* 获取线程池
*
* @return
*/
public static ThreadPoolExecutor getPoolExecutor() {
return (ThreadPoolExecutor) pool;
}
public static void shutdown() {
pool.shutdown();
}
public static void main(String[] args) throws InterruptedException {
System.out.println("come");
AsynchronousService.submit(new CcstudyCallable() {
@Override
public Object run() throws Exception {
System.out.println("in");
Thread.sleep(2 * 1000);
return null;
}
}, 1 * 1000);
System.out.println("end");
}
import java.util.concurrent.Callable;
/**
* 异步任务执行
* @author shenl
*
*/
public abstract class CcstudyCallable implements Callable {
protected String name;
private Object data;
public CcstudyCallable(){
this("");
}
public CcstudyCallable(String name){
this.name = name;
}
@Override
public Object call() throws Exception {
return run();
}
public abstract Object run() throws Exception;
public void setData(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
}