我必须在一个方法中调用多个webservice,每个webservice都由concurrent/parellel中的单独线程执行。每个网络服务将返回一个ArrayList
。注意:在这种情况下,有些web服务可能会失败或需要更多时间处理响应,我必须跳过这些失败结果。我怎样才能做到这一点?我试过这个sample code。在java中使用单独的线程调用多个webservice?
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()
返回类型为void所以如何返回结果?例子受到高度赞赏。我是多线程/并发线程概念的新手,所以如果我做错了任何事情,请指点我正确的方向。
嗨都铎王朝,我必须调用5个方法使用5个单独的线程我怎样才能实现这个使用上述可调用接口? –
@java_dev:你可以定义5个实现'Callable'的任务,每个调用一个服务,然后使用'runInParallel'方法将它们提交给'ExecutorService'。确保将线程数从2改为5. – Tudor
所以我必须编写5个任务类。实际上我必须调用5个webservices这些webservice必须调用call()方法或其他地方?每个webservice方法都会返回Arralylist。 –