码迷,mamicode.com
首页 > 编程语言 > 详细

java_有返回值线程_提前加载例子

时间:2015-08-29 23:03:19      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

package com.demo.test3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author QQ: 1236897
 *
 */

//有返回值线程
//提前加载
public class FutureTaskTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        long start = System.currentTimeMillis();
        PreLoad preLoad = new PreLoad();

        preLoad.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ProctInfo proctInfo = null;
        
        try {
            proctInfo = preLoad.get();
        } catch (DataLoadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        System.out.println(proctInfo.getId());
        
        long end = System.currentTimeMillis();
        
        System.out.println("Time - " + (end - start));
    }

}

class PreLoad {

    private final FutureTask<ProctInfo> future = new FutureTask<ProctInfo>(
            new Callable<ProctInfo>() {
                @Override
                public ProctInfo call() throws Exception {
                    // TODO Auto-generated method stub
                    Thread.sleep(6000);
                    return new ProctInfo();
                }

            });

    private final Thread thread = new Thread(future);

    public void start() {
        thread.start();
    }

    public ProctInfo get() throws DataLoadException, InterruptedException {

        try {
            return future.get();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            Throwable cause = e.getCause();
            if (cause instanceof DataLoadException) {
                throw (DataLoadException) cause;
            } else {
                throw launchThrowable(e);
            }
        }

    }
    
    public static RuntimeException launchThrowable(Throwable t){
        
        if(t instanceof RuntimeException){
            return (RuntimeException)t;
        }else if(t instanceof Error){
            throw (Error) t;
            
        }else{
            throw new IllegalStateException("Uncheck exception");
        }
        
    }
}

class ProctInfo {
    private String id = "111";

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

}

 

java_有返回值线程_提前加载例子

标签:

原文地址:http://www.cnblogs.com/MarchThree/p/4769860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!