-1

I took help from this Question

< Wait for all the threads to finish their job and then measure the time elapsed>

But this refernce doesn't solve my problem .May i am wrong at some points.

for (ReadProcess_MongoDB readData : readProcessMongoObj)
           executor.execute((Runnable) readData);
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.MINUTES);     
    } 
    catch (InterruptedException e) {
    //Log exception here
    } finally {

    executor.shutdownNow();
    printTime();
    }
public void printTime()
{
  for(int i=0;i<numberOfThreads;i++) 
        System.err.println("used Time "+timeArrObj[i]);

}

System prints data like this

Thread Number=3 MongoDB_readQuery used time 109
used Time 109
Thread Number=0 MongoDB_readQuery used time 109
used Time 109
used Time 0
used Time 0
used Time 0
Thread Number=2 MongoDB_readQuery used time 109
Thread Number=4 MongoDB_readQuery used time 109
Thread Number=1 MongoDB_readQuery used time 109

But i want display data

Thread Number=3 MongoDB_readQuery used time 109
Thread Number=0 MongoDB_readQuery used time 109
Thread Number=2 MongoDB_readQuery used time 109
Thread Number=4 MongoDB_readQuery used time 109
Thread Number=1 MongoDB_readQuery used time 109

used Time 109
used Time 0
used Time 0
used Time 0
used Time 109

I want execute printTime() after complete all thread.Please suggest where i made mistake

Community
  • 1
  • 1
user35662
  • 37
  • 1
  • 8
  • Have you tried the completion Services the guy mentioned in your reference? I don't see it in your example – d0x Dec 21 '14 at 19:08

2 Answers2

-1

It happens due to the Thread interleaving while printing the output. I guess the tasks submitted to executor is not long enough to block the awaitTermination method and executor gets shutdown immediately which in turn calls printTime() method in finally block.

Adding Thread.sleep() after awaitTermination() method call can provide a delay which can get you the output you were looking for.

Kumar V
  • 1,570
  • 1
  • 12
  • 19
-1

One of common solution here is to use CountDownLatch. Of course it will works fine if only you know how many tasks you have. If you don't know number of tasks You could try Phaser (and feel like cpt. Kirk). This solution is more flexible.

Koziołek
  • 2,791
  • 1
  • 28
  • 48