异步线程提交任务

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;
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值