public class ThreadForever { @Test public void demo() { ExecutorService service = Executors.newFixedThreadPool(3); // 如果是仅仅一个线程,就用Future 就够了,不需要CompletionService CompletionService completion = new ExecutorCompletionService(service); completion.submit(new Work()); // 此段可以启用一个新的线程单独执行,防止阻塞主线程 while (true) { try { System.out.println("Success:" + completion.take().get()); break; } catch (Exception e) { // 运行过程中出现了异常 e.printStackTrace(); completion.submit(new Work()); } } service.shutdown(); } class Work implements Callable { @Override public Boolean call() throws Exception { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "->" + i); // try { // Thread.sleep(100); // } catch (InterruptedException e) { // e.printStackTrace(); // } // 抛出异常,使线程中断 if (i % 3 == 1) { @SuppressWarnings("unused") int e = 1 / 0; } } return true; } } }