2013-02-26 38 views
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 (;;) { 

     } 
    } 
} 

} 

回答

0

下面的代码将不会返回if (name.equals("Thread0"))

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

    } 
} 

而你传递 “Thread0” 当我== 0:

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

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