我想在程序中创建一定数量的线程,其中要创建的线程数量由用户在运行时提供。有什么建议吗??
最佳答案
有多种方法可以做到这一点。 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/