TaskManager implements TaskListener<Task> { public static void waitForCompletion(final Task task) throws InterruptedException { if (task == null) { return; } TaskTerminationWaiter taskTerminationWaiter = new TaskTerminationWaiter( task); task.addTaskListener(taskTerminationWaiter); while (!task.getState().isFinished()) { 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 testWaitForCompletion() { FakeTask task1 = new FakeTask("fake task 1", 1, 1); Assert.assertEquals(TaskState.WAITING, task1.getState()); task1.start(); try { TaskManager.waitForCompletion(task1); } catch (InterruptedException e) { e.printStackTrace(); Assert.assertTrue("exception thrown : " + e.getMessage(), false); } Assert.assertEquals(TaskState.FINISHED, task1.getState()); Assert.assertEquals(1., task1.getProgress()); Assert.assertEquals(0, task1.getTaskListenerCount()); FakeTask task2 = new FakeTask("fake task 2", 10, 100); Assert.assertEquals(TaskState.WAITING, task2.getState()); task2.start(); try { TaskManager.waitForCompletion(task2); } catch (InterruptedException e) { e.printStackTrace(); Assert.assertTrue("exception thrown : " + e.getMessage(), false); } Assert.assertEquals(TaskState.FINISHED, task2.getState()); Assert.assertEquals(1., task2.getProgress()); Assert.assertEquals(0, task2.getTaskListenerCount()); }