`
AmwuYYGY
  • 浏览: 26752 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

实时政策接口取政策

    博客分类:
  • JAVA
 
阅读更多
要求传一个航班条件,实时的去查询51BOOK接口的政策和8000YI接口的政策,并返回结果。
为了性能问题,需要并行的去查两边的接口,最后合并返回结果。要个线程并行查政策的时候需要设置超时时间,如果超过设定的时间则不取该接口的政策。


示例代码:


package cn.tempus.prodcloud.service.qr;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class App {

	public static ExecutorService pool = Executors.newCachedThreadPool();//定义线程池
	
	public static void main(String[] args) {

		//定义任务集合
		List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
		//定义51BOOK任务,实际用时根据需要去改
		Callable<Integer> a51BOOK = new Callable<Integer>() {

			public Integer call() throws Exception {
				System.out.println("---111");
				TimeUnit.SECONDS.sleep(3);
				System.out.println("等等呀...");
				return 1;
			}
		};
		tasks.add(a51BOOK);

		Callable<Integer> b8000Yi = new Callable<Integer>() {

			public Integer call() throws Exception {
				System.out.println("---9999");
				TimeUnit.SECONDS.sleep(1);
				System.out.println("---9999");
				return 9999;
			}
		};
		tasks.add(b8000Yi);

		try {
			//调用并返回所有任务,超时时间为2秒
			List<Future<Integer>> futures = pool.invokeAll(tasks, 2, TimeUnit.SECONDS);
			for (Future<Integer> fs : futures) {
				Integer res;
				try {
					if (fs == null) {
						System.out.println("null....");
					}
					res = fs.get();
					System.out.println("返回结果:" + res);

				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		} catch (InterruptedException e) {
		}
		pool.shutdown();

		System.out.println("我是不是真的在等待...");
	}

}



执行返回结果:

---111
---9999
---9999
null
返回结果:9999
我是不是真的在等待...


0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics