gpt4 book ai didi

java - 如何动态创建线程?

转载 作者:行者123 更新时间:2023-12-02 07:54:02 25 4
gpt4 key购买 nike

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

最佳答案

有多种方法可以做到这一点。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com