我必須在一個方法中調用多個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。 –