java 异步处理

详情请看:http://www.cnblogs.com/yezhenhan/archive/2012/01/07/2315645.html

引入ExecutorService 类 

    private static final ExecutorService executes=Executors.newCachedThreadPool(); 

把需要处理的逻辑代码在放 run里面

需要传入参数 定义变量为final 类型

//定义变量为 final 
final long size = imageFile.getSize();

Runnable runnable = new Runnable() { public void run() { //处理代码 } }; executes.execute(runnable);

使用线程池 基类

/**
 * 线程池类
 * @ClassName ThreadPools.java 
 * @Description 
 * @author caijy
 * @date 2015年6月9日 上午10:50:38
 * @version 1.0.0
 */
public class ThreadPools {
    private ThreadPoolExecutor threadPool;//线程池
    private ThreadPools(){
        //初始200 最大400
        threadPool =  new ThreadPoolExecutor(200, 400, 1,
                TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>());

    }
    private static ThreadPools instance = new ThreadPools();
    /**
     * 获取线程池的单例对象
     * @return
     */
    public static ThreadPools getInstance()
    {
        return instance;
    }
    /**
     * 得到线程池
     * @return
     */
    public ThreadPoolExecutor getPools(){
        return threadPool;
    }
    /**
     * 提交线程
     * @param <V>
     * @param callable
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public <V> Future<V> submit(Callable<V> callable) throws InterruptedException, ExecutionException{
        return threadPool.submit(callable);
    }
    /**
     * 执行线程
     * @param command
     */
    public void execute(Runnable command){
        threadPool.execute(command);
    }
    /**
     * 关闭线程池
     * @throws Exception
     */
    public void shutDown() throws Exception{
        threadPool.shutdown();
    }

使用方式

    //获取线程池
        ThreadPools    instance=ThreadPools.getInstance();
        //拼接文件路劲
        final String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
        //拼接文件路劲
        final    String filePathNameTon = realPath + File.separator + pathName;
        final long size = imageFile.getSize();
        //保存图片成功后在 来压缩图片
           Runnable runnable = new Runnable() {
               public void run() {
               //处理逻辑     
                   
               }
           };
           instance.execute(runnable);

 

原文地址:https://www.cnblogs.com/miskis/p/5619379.html