ScheduledThreadPoolExecutor.remove:使用安全

时间:2013-07-16 23:47:03

标签: java multithreading threadpool

我正在尝试安排大量任务定期执行。在某些情况下,某些任务需要从调度中停止,所以我将它们从threadPoolExecutor的interal队列中删除。我是从任务本身那里做到的

以下是我的方法。我不确定从任务内部从threadPoolExecutor服务中删除任务的想法会导致任何问题。(查看同步方法名称'removeTask'。有没有更好的方法来完成我想在这里做的事情

public class SchedulerDaemon  {


    private ScheduledExecutorService taskScheduler;
    private ScheduledFuture taskResult1, taskResult2;
    private Task1 task1;
    private Task2 task2;


    public SchedulerDaemon(Task1 task, Task2 task2)
    {
        this.task1 = task1;
        this.task2 = task2;1
        taskScheduler = new ScheduledThreadPoolExecutor(1);
    }


    public void start() {
       if(taskScheduler == null) {
           taskScheduler = new ScheduledThreadPoolExecutor(1);
           taskResult = taskScheduler.scheduleAtFixedRate(new TaskWrapper(task1) , 60000,60000, TimeUnit.MILLISECONDS);
           taskResult2 = taskScheduler.scheduleAtFixedRate(new TaskWrapper(task2) , 60000,60000, TimeUnit.MILLISECONDS);

       }
    }


    public void stop() {
        if(taskScheduler != null) {
            taskScheduler.shutdown();
            taskResult1.cancel(false); 
            taskResult2.cancel(false);           
            taskScheduler = null;
            taskResult = null;
        }

    }

        public  synchronized void removeTask( TaskWrapper task){
            ((ScheduledThreadPoolExecutor) taskScheduler).remove(task);
        }

    class TaskWrapper implements Runnable {
        private Task myTask;

        public TaskWrapper(Task task) {
            myTask = task;
        }

        @Override
        public void run() {
            try {
               boolean keepRunningTask = myTask.call();
               if(!keepRunningTask) {

                   ***//Should this cause any problem??***
                   removeTask(this);
               }
            } catch (Exception e) {
                //the task threw an exception remove it from execution queue
                ***//Should this cause any problem??***
                removeTask(this);
            }
        }



    }
}


public Task1 implements Callable<Boolean> {

public Boolean call() {  
if(<something>)
return true;
else
return false;    
}
}



public Task2 implements Callable<Boolean> {

    public Boolean call() {  
    if(<something>)
    return true;
    else
    return false;    
    }
    }

2 个答案:

答案 0 :(得分:1)

每当您安排任务时

ScheduledFuture<?> future = schedulerService.scheduleAtFixedRate(new AnyTask());

返回Future Object。   使用此Future Object取消此任务。   试试这个

  future.cancel(true);

来自JavaDocs

  /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when <tt>cancel</tt> is called,
     * this task should never run.  If the task has already started,
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return <tt>true</tt>.  Subsequent calls to {@link #isCancelled}
     * will always return <tt>true</tt> if this method returned <tt>true</tt>.
     *
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return <tt>false</tt> if the task could not be cancelled,
     * typically because it has already completed normally;
     * <tt>true</tt> otherwise
     */ 

答案 1 :(得分:0)

强制取消任务是危险的,这就是为什么要从java中删除标记,所以, 或者你应该在你的线程中有一个共享标志......

类似的东西:我能活下去吗?我可以住吗?没有?好的回来!这个缝很大但是安全的方式!

相关问题