获取异常阻止ScheduledExecutorService

时间:2016-11-03 17:54:38

标签: java

以下代码,ScheduledExecutor有一项任务。在生产中它将有几个任务,但现在我正在测试一个。无论如何,我需要能够处理异常。我的下面的代码执行此操作,但导致我的GUI无响应。标记的线似乎是问题。我怎样才能收集所有例外情况?

  SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        CommandInterface ci = tc.getTask().getCommandInterface();
        ScheduledExecutorService scheduler = 
            taskManager.getComponentInterface().getThreadPool();
        ScheduledFuture<?> st = scheduler.schedule(
            new TimedRunnable(ci), new Date(
                ci.getScheduledDate().getTime()
                - System.currentTimeMillis()).getTime(), TimeUnit.MILLISECONDS);

                //This line causes blocking  -> 
        SwingUtilities.invokeLater(new AlertRunnable(
            taskManager.getComponentInterface().getAlertList(), st));
    }
  });

1 个答案:

答案 0 :(得分:0)

                SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    CommandInterface ci = tc.getTask().getCommandInterface();
                    taskManagerInterface.getComponentInterface().getThreadPool().schedule(new TimedRunnable(ci, taskManagerInterface.getComponentInterface()), new Date(ci.getScheduledDate().getTime() - System.currentTimeMillis()).getTime(), TimeUnit.MILLISECONDS);

                }
            });

定时运行:

    /**
 * This class runs at a specific time.
 */
public static class TimedRunnable implements Runnable, Serializable {

    ExecutorService workerExecutor = Executors.newSingleThreadExecutor();
    CommandInterface commandInterface;
    ComponentInterface componentInterface;

    public TimedRunnable(CommandInterface commandInterface, ComponentInterface componentInterface) {
        this.commandInterface = commandInterface;
        this.componentInterface = componentInterface;
    }

    @Override
    public void run() {
        //submit the callable to the progressHelper
        Future future = workerExecutor.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    ReturnInterface returnInterface = (ReturnInterface) commandInterface.call();
                    returnInterface.submitResult();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                return null;
            }
        });

        try {
            Object get = future.get();
        } catch (InterruptedException | ExecutionException ex) {
            Throwable cause = ex.getCause();
            Throwable cause1 = cause.getCause();

            if (cause1 instanceof CommandInterfaceException) {
                System.out.println("[MyItemTree].scheduleTask Cause 1= COMMANDINTERFACE EXCEPTION");
               this.componentInterface.getAlertList().addAlert(((CommandInterfaceException) cause1).getResolverFormInterface());
            }
        }

    }

}