如何在运行任务之前创建可以执行锅炉代码的Executor?

时间:2012-05-30 03:29:23

标签: java

我正在尝试建立一个并发结构,其中应该在某种类型的任务之前执行一些样板代码(以检查前置条件)。换句话说,我想在Executor将任务队列化后,但在它调用execute之前运行代码。怎么办呢?

1 个答案:

答案 0 :(得分:3)

使用装饰师?

public class TestExecutor{
    public static void main(String[] args){
        Executor e = Executors.newCachedThreadPool();
        e = new PreconditionCheckerExecutor(e){
            @Override
            protected void checkPrecondition(Runnable command){
                //do some precondition
            }
        };
        e.execute(/*myRunnable1*/);
        e.execute(/*myRunnable2*/);

    }
}
abstract class PreconditionCheckerExecutor implements Executor
{
    private final Executor executor;

    PreconditionCheckerExecutor(Executor executor) {
        this.executor = executor;
    }

    @Override
    public void execute(Runnable command) {
        checkPrecondition(command);
        executor.execute(command);
    }

    protected abstract void checkPrecondition(Runnable command);
}

如果需要,您可以使其更具体(例如,通过ExecutorService替换Executor),具体取决于您的需求。