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
Post a Comment