正确的方法使多个线程执行单个任务

发布于 2025-01-29 09:21:30 字数 752 浏览 2 评论 0原文

我正在尝试在一个间隔上执行单个函数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 技术交流群。

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

发布评论

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

评论(1

芯好空 2025-02-05 09:21:30

我不知道您的函数的上下文和目的是因为您没有足够提及,具体取决于上下文,您可能会在并行的多个线程(如同步问题)中遇到一些问题。但是,如果您的上下文不需要同步,则可以使用执行相同函数的多个线程。

如果您不需要真正的并行化,则此实现将要简单得多:

private int scheduleCount = 0; // Global to the class

//...

private void foo(int executionCount) {
    System.out.println(String.format("Schedule times %d, execution times %d", scheduleCount, i));
}

//...

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()-> {
    scheduleCount++;
    for(int i = 1; i <= 5; i++) {
        foo(i);
    }
}, 300, 300, TimeUnit.MILLISECONDS);

这是输出日志:

I/System.out: Schedule times 1, execution times 1
I/System.out: Schedule times 1, execution times 2
I/System.out: Schedule times 1, execution times 3
I/System.out: Schedule times 1, execution times 4
I/System.out: Schedule times 1, execution times 5
I/System.out: Schedule times 2, execution times 1
I/System.out: Schedule times 2, execution times 2
I/System.out: Schedule times 2, execution times 3
I/System.out: Schedule times 2, execution times 4
I/System.out: Schedule times 2, execution times 5
I/System.out: Schedule times 3, execution times 1
I/System.out: Schedule times 3, execution times 2
I/System.out: Schedule times 3, execution times 3
I/System.out: Schedule times 3, execution times 4
I/System.out: Schedule times 3, execution times 5
I/System.out: Schedule times 4, execution times 1
I/System.out: Schedule times 4, execution times 2
I/System.out: Schedule times 4, execution times 3
I/System.out: Schedule times 4, execution times 4
I/System.out: Schedule times 4, execution times 5

请注意,您可能需要一个句柄来安排的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:

private int scheduleCount = 0; // Global to the class

//...

private void foo(int executionCount) {
    System.out.println(String.format("Schedule times %d, execution times %d", scheduleCount, i));
}

//...

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()-> {
    scheduleCount++;
    for(int i = 1; i <= 5; i++) {
        foo(i);
    }
}, 300, 300, TimeUnit.MILLISECONDS);

Here is the output log:

I/System.out: Schedule times 1, execution times 1
I/System.out: Schedule times 1, execution times 2
I/System.out: Schedule times 1, execution times 3
I/System.out: Schedule times 1, execution times 4
I/System.out: Schedule times 1, execution times 5
I/System.out: Schedule times 2, execution times 1
I/System.out: Schedule times 2, execution times 2
I/System.out: Schedule times 2, execution times 3
I/System.out: Schedule times 2, execution times 4
I/System.out: Schedule times 2, execution times 5
I/System.out: Schedule times 3, execution times 1
I/System.out: Schedule times 3, execution times 2
I/System.out: Schedule times 3, execution times 3
I/System.out: Schedule times 3, execution times 4
I/System.out: Schedule times 3, execution times 5
I/System.out: Schedule times 4, execution times 1
I/System.out: Schedule times 4, execution times 2
I/System.out: Schedule times 4, execution times 3
I/System.out: Schedule times 4, execution times 4
I/System.out: Schedule times 4, execution times 5

Note that you may need a handle to scheduled executor service so that you can shut it down when it is no more needed.

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