我是 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 的固定线程池。我的循环最多运行 10 次。 1. 这里将创建和使用多少个线程。(根据我的观点,只使用了一个线程,因为我每次都用 future 对象取消。这是正确的吗?)
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);
}
}
}
关于java - 如果 future 在循环内,Java 中的 ExecutorService 会如何表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24795158/