在时间表上执行具有多个线程的单个任务

发布于 2025-01-28 15:21:19 字数 344 浏览 3 评论 0 原文

我有一个函数 foo()我想在间隔上被多个线程调用。示例:想要每100ms执行使用x线数量的foo()。我不确定该怎么做。

我正在寻找您可以在其中实例化具有数量工人的线程池。但是,当您使用此线程池调用时,它会一次耗尽所有线程并执行任务吗?

任何想法都将不胜感激;谢谢

I have a function foo() that I want to be invoked by multiple threads on an interval. example: want to execute foo() every 100ms with x number of threads. I am unsure how to go about it.

I am looking at FixedThreadPool where you can instantiate a thread pool with number of workers. However when you invoke using this thread pool does it exhaust all threads at once and executes a task?

any ideas would be appreciated; thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏日浅笑〃 2025-02-04 15:21:19

对于重复单个任务,您不需要多个线程。

使用单线线程计划的执行人服务

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

将任务定义为可运行 callable

Runnable task = … ;

安排重复执行。

ScheduledFuture future = ses.scheduleWithFixedDelay( task , 0 , 100 , TimeUnit.MILLISECONDS ) ;

所有这些已经在堆栈溢出上已经覆盖了很多次。搜索以了解更多。

For a single task being repeated, you do not need multiple threads.

Use a single-threaded scheduled executor service.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

Define your task as a Runnable or Callable.

Runnable task = … ;

Schedule for repeated execution.

ScheduledFuture future = ses.scheduleWithFixedDelay( task , 0 , 100 , TimeUnit.MILLISECONDS ) ;

All of this has been covered many times already on Stack Overflow. Search to learn more.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文