java - How to wait until all jobs are finished in thread pool? -


i have threadpool, please see code below. want before asserequals statement waited until jobs finished. how can achieved? awaittermination() works if shutdown called not want.

private volatile int = 0;  @test public void threadpooltest() throws interruptedexception {     executorservice  threadpool = executors.newfixedthreadpool(8);     threadpool.submit(new runnable() {         public void run() {             i++;         }     });     threadpool.submit(new runnable() {         public void run() {             i++;         }     });     assertequals(2,i);     threadpool .shutdown(); } 

try using countdownlatch : it's concurrency barrier can await n tasks counter :

@test public void threadpooltest() throws interruptedexception {     executorservice  threadpool = executors.newfixedthreadpool(8);      final countdownlatch latch = new countdownlatch(2);      threadpool.submit(new runnable() {         public void run() {             i++;             latch.countdown();         }     });     threadpool.submit(new runnable() {         public void run() {             i++;             latch.countdown();         }     });     latch.await();     assertequals(2,i);     threadpool .shutdown(); } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -