![](/img/trans.png)
[英]Java: How to break loop when using Executorservice and future for timer?
[英]How does ExecutorService in Java behave if future is inside a loop
我是java execuatorservice的新手。
我去網上扔了一些例子,但是我有一些基本的疑問。
我創建了如下的可調用類
public class ReadTest implements Callable<String> {
@Override
public String call() throws Exception {
return "OK";
}
}
我創建了我的主課,如下所示
public class ThreadMain {
public static void main(String args[]) {
try {
ExecutorService execuator = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Future<String> future;
System.out.println("I : " + i);
future = execuator.submit(new ReadTest());
System.out.println(future.get());
future.cancel(true);
}
execuator.shutdownNow();
} catch (Exception ex) {
System.out.println("Error : " + ex);
}
}
}
我正在創建具有限制5的FixedThreadPool。我的循環最多運行10次。 1.在這里將創建和使用多少個線程。(根據我的觀點,僅使用一個線程,因為我每次都用將來的對象取消。是否正確?)
2.我想執行上述for循環的多個任務。 我有使用jsch在shell中執行的命令列表。 如何用線程做到這一點?
任何幫助將不勝感激
您是否要運行異步任務,在等待時必須做其他事情? 也許這不是您想要的,但是您正在學習Java executorservice。 這個應用程序使用異步並發線程來尋找什么?
public class ThreadMain {
public static void main(String args[]) {
try {
// start async(threaded) workers
ExecutorService execuator = Executors.newFixedThreadPool(5);
List<Future<String>> workers = new ArrayList<Future<String>>();
for (int idx=0; idx < 10; idx++)
workers.add( execuator.submit(new ReadTest()) );
// loop until all workers is done, results may arrive in random order,
// if none is ready then do something else while waiting for next result.
while(!workers.isEmpty()) {
Future<String> worker=null;
for(int idx=0; idx < workers.size(); idx++) {
worker = workers.get(idx);
if (worker.isDone()) {
worker.remove(idx);
break;
}
worker = null;
}
if (worker==null) {
Thread.sleep(500); // do something else, like idle
} else {
System.out.println("Worker is done with results " + worker.get() );
}
}
execuator.shutdown();
} catch (Exception ex) {
System.out.println("Error : " + ex);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.