java - 如何使 A runnable 多次随机运行?

标签 java concurrency time random

假设您有 N 个可运行对象,并且您希望每个对象在随机时间段内执行。一旦可运行对象在该时间段内执行,您希望重新安排它运行另一个随机时间段。您希望能够多次为每个可运行对象执行此操作。

一旦 runnable 启动,它应该只是在无限循环中执行某些操作 - 也就是说 runnable 应该不知道它会运行多长时间。从 runnable 的角度来看,它将无限期地运行。

如何实现这一点,理想情况下仅使用标准 Java API?如果这不可能按原样实现,哪种替代设计最接近?

最佳答案

您可能会发现这更简单。

ScheduledExecutorService ses = ...
Runnable runnable = ...

new RandomExecutor(ses, runnable, 10, 10);
new RandomExecutor(ses, runnable, 10, 10);

// run for a random length of time and wait for a random length of time, repeat.
public class RandomExecutor implements Runnable {
    private static final Random rand = new Random();
    private ScheduledExecutorService ses;
    private Runnable runnable;
    private int maxRun;
    private int maxSleep;

    public RandomExecutor(ScheduledExecutorService ses, Runnable runnable, int maxRun, int maxSleep) {
        this.ses = ses;
        this.runnable = runnable;
        this.maxRun = maxRun;
        this.maxSleep = maxSleep;
        ses.execute(this);
    }

    @Override
    public void run() {
        long end = System.currentTimeMillis() + rand.nextInt(maxRun);
        do {
            runnable.run();
        } while(end > System.currentTimeMillis());
        ses.schedule(this, rand.nextInt(maxSleep)+1, TimeUnit.MILLISECONDS);
    }
}

关于java - 如何使 A runnable 多次随机运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3125502/

相关文章:

java - 仅当外部类参数化时内部接口(interface)才会生成错误?为什么?

c# - 搜索大型 ConcurrentBag?

java.util.ConcurrentModificationException : Unexpected List modification while multithreading?

java - 等待一批 future 完成时超时?

mysql - 验证 MySQL 中的时间格式有效性

java - 在 Java 的子类中实现抽象方法

java - Joda Time : Formatting with multiple formats with single Formatter

PHP检查时间是否在范围内,质疑通用解决方案

mysql - MySql数据库中的时间格式

Java Swing JButton 时间延迟(闪烁)