You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为现有Java EventWrapper类新增ifThen、pauseFor等流程控制方法

实现方案

核心逻辑基于你现有设计扩展:所有控制逻辑都封装为Runnable加入任务列表,execute执行时按添加顺序依次运行,完全兼容链式调用的要求。

完整实现代码

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EventWrapper
{
    // 内置默认公共线程池,也支持自定义传入
    private static final ExecutorService DEFAULT_EXECUTOR = Executors.newCachedThreadPool();
    private final ExecutorService executor;
    private final List<Runnable> _wrappers = new ArrayList<>();

    public EventWrapper() {
        this(DEFAULT_EXECUTOR);
    }

    public EventWrapper(ExecutorService executor) {
        this.executor = executor;
    }

    public EventWrapper add(final Runnable runnable)
    {
        _wrappers.add(runnable);
        return this;
    }

    /**
     * 暂停执行指定时长
     * @param duration 暂停时长
     */
    public EventWrapper pauseFor(Duration duration) {
        _wrappers.add(() -> {
            try {
                Thread.sleep(duration.toMillis());
            } catch (InterruptedException e) {
                // 恢复中断标记,不吞中断信号
                Thread.currentThread().interrupt();
                throw new RuntimeException("执行暂停时被中断", e);
            }
        });
        return this;
    }

    /**
     * 条件满足时执行对应任务
     * @param condition 判定条件
     * @param runnable 条件为真时执行的任务
     */
    public EventWrapper ifThen(boolean condition, Runnable runnable) {
        _wrappers.add(() -> {
            if (condition) {
                runnable.run();
            }
        });
        return this;
    }

    /**
     * 异步执行任务,默认不阻塞后续流程
     * 如需等待异步任务完成再执行后续,可替换为下方注释中的实现
     * @param runnable 异步执行的任务
     */
    public EventWrapper addAsync(Runnable runnable) {
        _wrappers.add(() -> executor.submit(runnable));
        return this;
    }

    /* 如需阻塞等待异步任务完成再执行后续任务,使用该版本实现
    public EventWrapper addAsync(Runnable runnable) {
        _wrappers.add(() -> {
            try {
                executor.submit(runnable).get();
            } catch (Exception e) {
                throw new RuntimeException("异步任务执行失败", e);
            }
        });
        return this;
    }
    */

    public void execute()
    {
        _wrappers.forEach(Runnable::run);
    }

    public static EventWrapper newWrapper()
    {
        return new EventWrapper();
    }

    public static EventWrapper newWrapper(ExecutorService executor)
    {
        return new EventWrapper(executor);
    }
}

注意事项

  • 你给出的示例代码中方法名写为addAsyn属于拼写遗漏,若要完全匹配示例,直接将方法名改为addAsyn即可。
  • 内置默认线程池为无界缓存线程池,适合短任务场景,如果是长任务场景建议自行传入自定义线程池实例,避免资源耗尽。
  • 中断异常处理保留了线程中断状态,符合Java并发编程规范,避免出现中断信号丢失的问题。

内容的提问来源于stack exchange,提问作者Girls are beautiful

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:09:03