带返回值的多线程

参考地址:http://blog.51cto.com/lavasoft/222082

为了提高执行效率,有时可以采用多线程执行

1、每个线程执行的方法一样

import java.util.concurrent.*; 

/** 
* Java线程:有返回值的线程 
* 
* @author Administrator 2009-11-5 0:41:50 
*/ 
public class Test { 
        public static void main(String[] args) throws ExecutionException, InterruptedException { 
                //创建一个线程池 
                ExecutorService pool = Executors.newFixedThreadPool(2); 
                //创建两个有返回值的任务 
                Callable c1 = new MyCallable("A"); 
                Callable c2 = new MyCallable("B"); 
                //执行任务并获取Future对象 
                Future f1 = pool.submit(c1); 
                Future f2 = pool.submit(c2); 
                //从Future对象上获取任务的返回值,并输出到控制台 
                System.out.println(">>>"+f1.get().toString()); 
                System.out.println(">>>"+f2.get().toString()); 
                //关闭线程池 
                pool.shutdown(); 
        } 
} 

class MyCallable implements Callable{ 
        private String oid; 

        MyCallable(String oid) { 
                this.oid = oid; 
        } 

        @Override 
        public Object call() throws Exception { 
               //具体执行的代码
                return oid+"任务返回的内容"; 
        } 
}

2、每个线程执行的任务不一样

import java.util.concurrent.*; 

/** 
* Java线程:有返回值的线程 
* 
* @author Administrator 2009-11-5 0:41:50 
*/ 
public class Test { 
        public static void main(String[] args) throws ExecutionException, InterruptedException { 
                //创建一个线程池 
                ExecutorService pool = Executors.newFixedThreadPool(2); 
                //创建两个有返回值的任务 
               // 查询最新的结果
        Callable<JSONObject> c1 = new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orgId", _orgId);
                JSONObject queryStr = 
                                HttpHelper.SINGLON.query("findOrgDataitem", jsonObject);
                return queryStr;
            }
        };
               // 查询历史版本结果
        Callable<JSONObject> c2= new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                File file = new File(
                          FileCatalog.DATAITEM_HISTORY.getPath(_request, _orgId.toString(), _nearlyVersion, INFO_JSON));
                if (!file.exists()) {
                    return null;
                }
                String read = FileUtils.readFileToString(file, SysConstant.CSN);
                if (StringUtils.isBlank(read)) {
                    return null;
                }
                return new JSONObject(read);
            }
        };
                //执行任务并获取Future对象 
                Future f1 = pool.submit(c1); 
                Future f2 = pool.submit(c2); 
                //从Future对象上获取任务的返回值,并输出到控制台 
                System.out.println(">>>"+f1.get().toString()); 
                System.out.println(">>>"+f2.get().toString()); 
                //关闭线程池 
                pool.shutdown(); 
        } 
} 

要深入了解还需要看Callable和Future接口的API。

ps.在xml文件中配置线程池

<!-- 线程池配置 -->
    <bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" scope="singleton">
        <!-- 核心线程数  -->
        <property name="corePoolSize" value="10" />
        <!-- 最大线程数 -->
        <property name="maxPoolSize" value="50" />
        <!-- 队列最大长度 -->
        <property name="queueCapacity" value="1000" />
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="300" />
        <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>

猜你喜欢

转载自www.cnblogs.com/cq-yangzhou/p/10109196.html