Thread job in Java

I want to generate 200 threads in Java at the same time What I'm doing now is entering the loop and creating 200 threads and starting them After completing these 200 threads, I want to generate another 200 threads, and so on

The point here is that the first 200 threads I generate need to be completed before generating the next group I tried the following code, but it didn't work

for(int i=0;i<200;i++){
    Thread myThread = new Thread(runnableInstance);
    myThread.start();
}
for(int i=0;i<200;i++){
    Thread myThread = new Thread(runnableInstance);
    myThread.start();
}

Note: I deliberately put the for loop twice, but the effect I want is not because the second for loop executes before the first set of threads ends

Please give me some advice

Solution

You should keep the list of threads created Then, once all this is started, you can traverse the list and perform a connection on each list When the join loop ends, all threads will finish running

List<Thread> threads = new List<Thread>();
for(int i=0;i<200;i++){
    Thread myThread = new Thread(runnableInstance);
    myThread.start();
    threads.add(myThread);
}
//All threads are running
for(Thread t : threads) {
    t.join();
}
//All threads are done
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>