有没有办法完全停止Java中的任务?

时间:2018-08-28 10:54:27

标签: java multithreading

如果任务没有在要求的时间内完成,我希望任务按计划的时间间隔和超时运行,并继续进行进一步的迭代

我已经回答了以下问题,但是并不能解决我的问题。

How do you kill a Thread in Java?

ExecutorService that interrupts tasks after a timeout

考虑以下情况

    BasicThreadFactory collectionFactory = new BasicThreadFactory.Builder()
            .namingPattern("CollectionExecutor-%d")
            .build();
    // thread pool size is set 2
    // 1-for scheduler thread which runs task and tracks timeout
    // 2-for task itself
    ScheduledExecutorService collectionExecuter = 
            Executors.newScheduledThreadPool(2, collectionFactory);
    // fires collection every minute and if it is in between execution during
    // scheduled time then waits for completion and executes immediately
    // after it

    //my task:
    Runnable runnable= new Runnable() {

        @Override
            public void run() {
        try {
            System.out.println("Executed started");
            Thread.sleep(2000);
            System.out.println("Executed after .get method call.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(20000);
            System.out.println("Executed even after .cancel method " +
                    "call (I want this to avoid this.)");
        } catch (Exception e) {
            e.printStackTrace();
        }               
    }
};

上面的任务应该以3秒的间隔运行,并且如果花费的时间超过1秒则停止...考虑一下不可能在单个try catch块中完成任务,现在我如何才能停止任务以进一步等待在下一个睡眠(20000)中,并继续下一次迭代。

    collectionExecuter.scheduleAtFixedRate(new Runnable() {//scheduler thread
        @Override
        public void run() {
            try {
                Future<?> future = collectionExecuter.submit(runnable);
                try {
                    future.get(1, TimeUnit.SECONDS);

                } catch (Exception e) {
                    future.cancel(true);
                    System.out.println("Collection thread did not " +
                           "completed in 1 Sec.Thread Interrupted");
                }
            } catch (Exception e) {
                System.out.println("Unable to start Collection Thread");
            }
        }
    }, 0, 3, TimeUnit.SECONDS);
}

0 个答案:

没有答案