How to create threads dynamically? [closed]

天涯浪子 提交于 2019-12-12 02:31:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!