0
我知道future.get()
是一種阻塞方法。我有一個簡單的類,在for循環中提交任務,每個任務打印線程的名稱。 當我在一個循環中使用Executors.newCachedThreadPool()
和future.get()
時,據我瞭解,每個循環都是一個同步流,並且不應該有TimeOut異常的範圍。 但我注意到這個例外。有人可以建議爲什麼發生這種情況。使用Future.get()的超時異常() - Java ThreadPools
的代碼如下:
public class AsynchronusExecutorTest {
private static ExecutorService executor = null;
static {
executor = Executors.newCachedThreadPool();
System.out.println("New executor");
}
public static void main(String[] args) {
for (int i = 0;; i++) {
final Future<?> future = executor.submit(new MyRunnable3("Thread" + i));
try {
future.get(1, TimeUnit.SECONDS);
System.out.println("Thread returns");
} catch (Exception e) {
System.out.println("Time out occured Exception: " + e);
e.printStackTrace();
future.cancel(true);
}
}
}
}
class MyRunnable3 implements Runnable {
String name;
public MyRunnable3(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("This is test " + name);
if (name.equals("Thread0")) {
for (;;) {
}
}
}
}