问题
I want to create certain number of threads in my program where the number of threads to be created is provided by the user at run-time. Any suggestions ??
回答1:
There are a number of ways to do this. A for loop is the easiest:
Thread[] threads = new Thread[numThreadsToCreate];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(yourRunnable);
threads[i].start();
}
Your Runnable couple be something like this:
private class MyRunnable implements Runnable {
public void run() {
// your code to run in the thread goes here
}
}
来源:https://stackoverflow.com/questions/9874587/how-to-create-threads-dynamically