我必须在一个方法中调用多个webservice,每个webservice由并发/ parellel中的单独线程执行。每个Web服务都将返回一个ArrayList
。注意:在这种情况下,某些web服务可能会失败或者需要更多时间来处理响应,我必须跳过这些失败结果。我怎样才能做到这一点?我试过这个sample code。
public class MultiThreadsEx{
public class Task implements Runnable {
private Object result;
private String id;
int maxRowCount = 0;
public Task(String id) {
this.id = id;
}
public Object getResult() {
return result;
}
public void run() {
try {
System.out.println("Running id=" + id+" at "+Utilities.getCurrentJavaDate("DD/MM/YYYY HH:MM:SS"));
if(id.equalsIgnoreCase("1")){
/**Getting Details from Amazon WS*/
maxRowCount = AmazonUtils.getweather(cityname);
}else if(id.equalsIgnoreCase("2")){
/**Getting Details from Google WS* /
maxRowCount = GoogleUtils.getWeather(cityName);
}
// call web service
//Thread.sleep(1000);
//result = id + " more";
result = maxRowCount;
} catch (InterruptedException e) {
// TODO do something with the error
throw new RuntimeException("caught InterruptedException", e);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void runInParallel(Runnable runnable1, Runnable runnable2) {
try {
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
t1.start();
t2.start();
} catch (Exception e) {
// TODO do something nice with exception
throw new RuntimeException("caught InterruptedException", e);
}
}
public void foo() {
try {
Task task1 = new Task("1");
Task task2 = new Task("2");
runInParallel(task1, task2);
System.out.println("task1 = " + task1.getResult()+" at "+Utilities.getCurrentJavaDate("DD/MM/YYYY HH:MM:SS"));
System.out.println("task2 = " + task2.getResult()+" at "+Utilities.getCurrentJavaDate("DD/MM/YYYY HH:MM:SS"));
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
但是run()
返回类型是无效的,那么如何返回结果呢?例子受到高度赞赏。我是多线程/并发线程概念的新手,所以如果我做错了什么,请指出我正确的方向。
答案 0 :(得分:2)
考虑将Runnable - run
替换为Callable - call
。这将允许您从线程任务返回结果:
public class Task implements Callable<Object> {
private Object result;
public Object call() {
// compute result
return result;
}
}
现在使用ExecutorService
:
public static void runInParallel(Callable<Object> c1, Callable<Object> c2) {
ExecutorService exec = Executors.newFixedThreadPool(2);
Future<Object> f1 = exec.submit(c1);
Future<Object> f2 = exec.submit(c2);
}
稍后在代码中,您可以使用f1.get()
和f2.get()
等待任务的结果。
答案 1 :(得分:0)
将Runnable的结果传递回创建它的对象的常用方法是将创建对象传递给Runnable的构造函数。任务完成后,您可以在创建对象中调用方法并传递结果数据。