使用future.get()的超时异常 - Java ThreadPools

时间:2013-02-26 07:52:30

标签: threadpool

我了解future.get()是一种阻止方法。我有一个简单的类,它在for循环中提交任务,每个任务都打印一个Thread的名称。 当我在循环中使用Executors.newCachedThreadPool()future.get()时,据我所知,每个循环都是一个同步流,并且不应该有TimeOut异常的范围。 但我注意到这个异常即将来临。有人可以说明为什么会这样。

代码如下:

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 (;;) {

        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

以下代码永远不会返回if (name.equals("Thread0"))

if (name.equals("Thread0")) {
    for (;;) {

    }
}

当你= = 0时传递“Thread0”:

for (int i = 0;; i++) {
    final Future<?> future = executor.submit(new MyRunnable3("Thread" + i));
    //...
}

您可能希望将for (int i = 0;; i++)更改为for (int i = 1;; i++)