gpt4 book ai didi

java - 在指定的超时后从一个线程执行多个 Runnable

转载 作者:行者123 更新时间:2023-12-02 00:30:26 25 4
gpt4 key购买 nike

我想安排 Runnables 并从同一线程中依次执行它们,但不能更早,然后在指定的超时后执行。有标准的方法吗?

这是我的代码:

public class DelayedExecutor {
private final long _timeout;
private final List<Runnable> _tasks = new LinkedList<>();
private final ThreadFactory _factory;
private final Thread _supervisor;

public DelayedExecutor(long timeout, ThreadFactory factory) {
_timeout = timeout;
_factory = factory;

_supervisor = new Thread(new Runnable() {
@Override
public void run() {
while (_supervisor.isInterrupted()) {
try {
Thread.sleep(_timeout);
}
catch (InterruptedException e) {
if (_supervisor.isInterrupted())
break;
}

synchronized (_tasks) {
ArrayList<Runnable> prepared = new ArrayList<>(_tasks);
Collections.reverse(prepared);

execute(prepared);

_tasks.clear();
}
}
}
});

_supervisor.setDaemon(true);
_supervisor.start();
}

public void schedule(Runnable runnable) {
synchronized (_tasks) {
_tasks.add(runnable);
}
}

private void execute(final List<Runnable> tasks) {
_factory.newThread(new Runnable() {
@Override
public void run() {
for (Runnable runnable : tasks)
runnable.run();
}
});
}
}

最佳答案

经过一些尖锐的评论后,我想我开始理解你在做什么,它看起来像是经过小修改的 Producer/Consumer 模式。根据我们的聊天,我现在了解到您希望以固定速率运行消费者!这应该会给您一个想法(但在您的实现中使用并发集合):

public FixedRateConsumer implements Runnable
{
private final object _lock = new object();
// *** use a concurrent collection here ***
private Queue<Runnable> _workQueue;

public FixedRateConsumer()
{
_workQueue = new Queue<Runnable>();
}

public scheduleTask(Runnable task)
{
synchronized(_lock)
{
_workQueue.put(task);
}
}

public void run()
{
synchronized(_lock)
{
while(_workQueue.poll()!=null)
{
_workQueue.take().run();
}
}
}
}

现在您只需安排消费者以固定速率运行即可:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
FixedRateConsumer consumer = new FixedRateConsumer();

scheduler.scheduleAtFixedRate(consumer, /*specify initial delay*/, /*specify rate*/, /*specify TimeUnit*/);

您的制作人可以安排这样的任务:

// Then you just schedule your tasks like this
consumer.scheduleTask(new Runnable());

关于java - 在指定的超时后从一个线程执行多个 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9180616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com