多线程应用 —— Future+Callable

业务场景

调用第三方接口,对方一次最多返回30条数据,想查取更多条数据时,使用多线程多次取值,最后整合数据,获取想要结果集。

Spring 配置线程池

<bean id="queryFlightLowPriceExecutor" 
	    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
	    <!--  核心线程数,默认为1-->
	    <property name="corePoolSize" value="3" /> 
	   <!--   最大线程数,默认为Integer.MAX_VALUE-->
	    <property name="maxPoolSize" value="20" /> 
	    <property name="queueCapacity" value="1000" />
	  <!--    线程池维护线程所允许的空闲时间,默认为60s-->
	    <property name="keepAliveSeconds" value="100" />     
    </bean>

实现Callable接口

class MyThread implements Callable<String> {//创建一个类  实现Callable接口,Callable的好处是,调用线程之后可以拿到线程的返回值
		private String request;
		private QueryFlightLowPrice10 queryFlightLowPrice10;
		
		public MyThread(String request,QueryFlightLowPrice10 queryFlightLowPrice10){//构造器这 就是new MyThread的是后 往里传参
			this.request = request;
			this.queryFlightLowPrice10 = queryFlightLowPrice10;
		}
        @Override
        public QueryFlightLowPrice10 call() throws Exception {//重写Callable的call方法
        
			String result =request;
		
			return result ;//返回值要跟Callable的泛型相同
        }
    }

创建多线程并取值

//线程池
private ThreadPoolTaskExecutor queryFlightLowPriceExecutor = SpringCtxHelper.getBean("queryFlightLowPriceExecutor");


//测试写死参数
		int days = 62;
		String request = "hxx";
		
		List<Future<String>> futureList = new ArrayList<Future<String>>();//----------String
		
		if(days>31){
			for(int i=0;i<days/31;i++){
				MyThread queryFlightLowPriceCallable = new MyThread(request+i);
				 Future<String> aa= queryFlightLowPriceExecutor.submit(queryFlightLowPriceCallable);
				 futureList.add(aa);
			}
		}
		//取结果
		String lastRequest="";//-------------
		for (Future<String> future : futureList) {
            while (true) {
                if (future.isDone() && !future.isCancelled()) {
                	String result = future.get();//*******************
                	
                	lastRequest+=result;
                    break;
                } else {
                    Thread.sleep(1000);
                }
            }
		}
		System.out.println(lastRequest);//-----------------
发布了60 篇原创文章 · 获赞 121 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/han_xiaoxue/article/details/90601072