TaskManager implements TaskListener<Task> { public static void startAndWait(final Task task) throws InterruptedException { if (task == null) { return; } TaskTerminationWaiter taskTerminationWaiter = new TaskTerminationWaiter( task); task.addTaskListener(taskTerminationWaiter); if (task.getState().isRunning() == false) { task.start(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread th, Throwable ex) { logger.error("Uncaught exception from task " + task.getName() + ": " + ex); ex.printStackTrace(); } }); } while (task.getState().isRunning() || task.getState() == TaskState.WAITING) { synchronized (task) { task.wait(100); } } task.removeTaskListener(taskTerminationWaiter); } TaskManager(); int getMaximumRunningThreadNumber(); void setMaximumRunningThreadNumber(int maximumRunningThreadNumber); boolean addTask(final Task task); boolean removeRunningTask(final Task task); int getPendingTaskCount(); int getRunningTaskCount(); @Override void onStateChange(Task task, TaskState oldState); boolean addTaskManagerListener(TaskManagerListener listener); boolean removeTaskManagerListener(TaskManagerListener listener); void removeAllTaskManagers(); static void startAndWait(final Task task); static void waitForCompletion(final Task task);  }
@Test public void testStartAndWait() { FakeTask task = new FakeTask("fake task 0", 100, 10); Assert.assertEquals(TaskState.WAITING, task.getState()); try { TaskManager.startAndWait(task); } catch (InterruptedException e) { e.printStackTrace(); Assert.assertTrue("exception thrown : " + e.getMessage(), false); } Assert.assertEquals(TaskState.FINISHED, task.getState()); Assert.assertEquals(1., task.getProgress()); Assert.assertEquals(0, task.getTaskListenerCount()); }