学习地址:
https://blog.csdn.net/qq_25806863/article/details/71126867
1. 同步并发获取结果:
// 开通3个同步线程 空闲下进行
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Callable<Object>> searchTasks = new ArrayList<Callable<Object>>();
// 根据查询shop 线程
Callable<Object> shopCall = new ShopCall();
searchTasks.add(shopCall);
searchTasks.add(shopCall);
searchTasks.add(shopCall);
//invokeAll 第一个参数是任务列表;第二个参数是过期时间;第三个是过期时间单位
try {
logger.debug(">>> Starting runing thread");
List<Future<Object>> futures = executorService.invokeAll(searchTasks,20, TimeUnit.SECONDS);
jsonObject.put("shop", futures.get(0).get());
executorService.shutdown();
} catch (Exception e) {
logger.error("Thread Error:{}",e);
throw new RuntimeException("异步获取数据失败: "+e.getMessage());
}
/**
* 获取用户信息
*
*
*
*/
private class ShopCall implements Callable<Object>{
public ShopCall() {
}
@Override
public Object call() throws Exception {
logger.debug(">>> Geting shop information:{}",slug);
return null ;
}
}
异步后台线程:不关心结果
// 后台异步执行 execute
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.execute(myRunnable);
executorService.execute(myRunnable);
executorService.execute(myRunnable);
executorService.shutdown();
System.out.println("返回数据");
}