有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如何在java中每Y秒创建X个任务(线程)?

我有1000个30秒的RTP流,每个流需要流到服务器,每个流应该在不同的线程上运行

目前,由于初始化延迟,我只是使用一个循环来创建这些线程并启动任务。我希望在初始化时分散一些负载,并从每秒~3.5-20个线程开始

最好的方法是什么


共 (2) 个答案

  1. # 1 楼答案

    与其按需创建单个线程,不如使用线程池。在Java中,线程创建涉及时间开销。线程池克服了这种延迟

    Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

    参考:JavaOfficialDocs

    “ExecutorService”用于使用线程池执行作业。这克服了每次调用的线程创建开销

    参考文献:[http://tutorials.jenkov.com/java-util-concurrent/executorservice.html]

    另外,请查看Java7中引入的“ForkJoinPool”,它具有“窃取工作”功能,即空线程从繁忙线程获取工作的能力

    参考文献:[http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.html]

  2. # 2 楼答案

    你应该仔细阅读ExecutorService框架,并决定哪个执行者案例最适合你

    非常基本的例子:

        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 1000; i++) {
            Runnable worker = new WorkerThread('' + i);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    

    你可能不想要1000个同时的Thread,而是一个ThreadPool

    此外,如果希望延迟或按计划启动线程,请参阅ScheduledThreadPoolExecutor