Working with threads in Java

I want to create 200 threads simultaneously in Java. What I'm doing right now starts in a loop and creates 200 threads and starts them. After these 200 are complete, I want to create another 200 sets of threads, etc.

The bottom line here is that the first 200 threads that I spawned must be COMPLETED before laying out the next set. I tried the code below but its not working

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 intentionally set the for Twice loop, but the desired effect that I intend does not happen simply because the second loop of the loop executes before the first set of threads completes their execution.

Please inform

+3
source share
6 answers

, . , , join . , .

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
+16

, ...

spawnAndWait() {
 Thread T[] = new Thread[n];
 for(int i=0;i<n;i++){
     T[i] = new Thread(runnableInstance);
     T[i].start();
 }
 for (Thread t : T) {
  t.join();
 }
}
+7

Java 1.5, , Java 1.4.2, - backport, .

, ; , ExecutorService, Future return, , . - , , , : -).

:

BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
taskExecutor = new ThreadPoolExecutor(200, 200, 30, TimeUnit.SECONDS, workQueue);

futureList.add(taskExecutor.submit(new MyCallable()));

for (Future<Object> future : futureList) {
    future.get(); // wait for the task to complete
}

//... instantiate your second group of executors
+7

Regarding pseudo code, you can specify the calling call ;-)

while( moreThreads ) {
    List<Callable<Integer>> threads = new ArrayList<Callable<Integer>>();
    for( int i = 0; i < 200; ++i ) {
        threads.add(new Callable<Integer>() );
    }

    FixedThreadPool pool = Executers.newFixedThreadPool(200);
    pool.invokeAll(threads);
    pool.shutdown();
}
+1
source

You need to wait for the threads to finish using join():

// run first set of threads
List<Thread> threads = threadsList; // save reference to all threads
for(Thread t : threads){
    t.join();
}
// all threads finished

// run other set of threads
0
source

Another solution is to use Latch

final CountDownLatch latch = new CountDownLatch(200);

  for(int i=0; i<10; i++)
{

 Thread thread = new Thread()
{
    public void run()
{
     try{
         //do your work  

     }finally{
      latch.countDown();
     }
    }
   };

     }  
            //will block here util your threads all finished
  latch.await();
0
source

Source: https://habr.com/ru/post/1746239/


All Articles