java - 如何动态创建线程?

标签 java multithreading dynamic

我想在程序中创建一定数量的线程,其中要创建的线程数量由用户在运行时提供。有什么建议吗??

最佳答案

有多种方法可以做到这一点。 for 循环是最简单的:

Thread[] threads = new Thread[numThreadsToCreate];
for (int i = 0; i < threads.length; i++) {
    threads[i] = new Thread(yourRunnable);
    threads[i].start();
}

您的Runnable可能是这样的:

private class MyRunnable implements Runnable {
    public void run() {
        // your code to run in the thread goes here
    }
}

您还可以使用线程池:

ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < NUM_THREADS; i++) {
    threadPool.submit(yourRunnable);
}
// shutdown the pool once we submit the last job, they will continue to run
threadPool.shutdown();

关于java - 如何动态创建线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874587/

相关文章:

java - 多线程环境下的readTimeout

java - 如何消除 JButton 行边缘和父 JPanel 边缘之间的间隙?

c# - 线程 : Why does this code show 5 in output in thread

c++ - 卡在 _dl_sysinfo_int80 上的多线程应用程序

c# - 组合表达式列表中的表达式

c# - 具有通用方法和属性的两个类

C++删除动态数组的一部分

java - 在java中实现快速排序时的无限循环/递归

java - java 8 中要映射的对象数组列表

c# - 如果作为单独的任务启动,有没有办法取消 Parallel.ForEach 循环