正确的方法使多个线程执行单个任务
我正在尝试在一个间隔上执行单个函数foo
,并且每个间隔多次。
我目前正在这样做的方式是通过创建使用指定的任何内容的newscheduledthreadpool
创建服务(在此示例中说5)。因此,预定的线程池将用5个池实例化。
这是正确的方法吗?
当前,每个间隔都执行5次功能(在功能中放置一个打印语句,并看到每个间隔打印5次),但想检查这是否是此用例的正确方法。
service = Executors.newScheduledThreadPool(threadPoolSize, runnable -> {
Thread t = new Thread(runnable, "Test");
t.setDaemon(true);
return t;
});
this.start();
}
void start() {
long initialDelay = frequencySecs + ThreadLocalRandom.current().nextInt(frequencySecs);
for (int i = 0; i < threadPoolSize; i++) {
service.scheduleAtFixedRate(this::foo, initialDelay, frequencySecs, MILLISECONDS);
}
}
I am trying to execute a single function foo
on an interval, and MULTIPLE times per interval.
The way I am currently doing it is by creating a service with a newScheduledThreadPool
of whatever is specified (let's say 5 for this example). So the scheduled thread pool will be instantiated with a pool of 5.
Would this be the correct way to go about it?
Currently is executing the function 5 times at every interval (put a print statement in the function and seeing it print out 5 times every interval), but wanted to check if this is the right approach for this use case.
service = Executors.newScheduledThreadPool(threadPoolSize, runnable -> {
Thread t = new Thread(runnable, "Test");
t.setDaemon(true);
return t;
});
this.start();
}
void start() {
long initialDelay = frequencySecs + ThreadLocalRandom.current().nextInt(frequencySecs);
for (int i = 0; i < threadPoolSize; i++) {
service.scheduleAtFixedRate(this::foo, initialDelay, frequencySecs, MILLISECONDS);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道您的函数的上下文和目的是因为您没有足够提及,具体取决于上下文,您可能会在并行的多个线程(如同步问题)中遇到一些问题。但是,如果您的上下文不需要同步,则可以使用执行相同函数的多个线程。
如果您不需要真正的并行化,则此实现将要简单得多:
这是输出日志:
请注意,您可能需要一个句柄来安排的executor服务,以便在不需要的情况下可以将其关闭。
I don't know what your function's context and purpose is cause you didn't mention enough, depending on the context, you may have some problems with multiple threads in parallel like synchronization issues. But if your context needs not synchronization you can use multiple threads that executing same function.
This implementation would be much simpler if you do not need real parallelisation:
Here is the output log:
Note that you may need a handle to scheduled executor service so that you can shut it down when it is no more needed.