1

我正在尝试设置一个并发结构,其中应该在某种类型的任务之前执行一些样板代码(以检查前置条件)。换句话说,我想在 Executor 将任务出列之后,但在它调用 execute 之前运行代码。如何才能做到这一点?

4

1 回答 1

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)。

于 2012-05-30T04:12:05.043 回答