0

我知道这future.get()是一种阻塞方法。我有一个简单的类,它在 for 循环中提交任务,每个任务打印线程的名称。当我在循环中使用Executors.newCachedThreadPool()andfuture.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 (;;) {

        }
    }
}

}
4

1 回答 1

0

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

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

    }
}

当 i == 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++).

于 2013-02-26T09:15:34.663 回答