This week's book giveaway is in the Java in General forum.
We're giving away four copies of Java by Comparison (eBook) and have Simon Harrer, Jörg Lenhard, Linus Dietz on-line!
See this thread for details.
Win a copy of Java by Comparison (eBook) this week in the Java in General forum!

Rony Dsouza

Greenhorn
+ Follow
since Aug 15, 2011
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Rony Dsouza

Chris Hurst wrote:Your last thread is very inefficient ...



Think about what this is doing it attempting to murder the CPU checking why the threads haven't finished (they are being delayed by this thread burning lots of CPU unless you have enough cores), its like a nagging child in a car saying are we there yet i.e. putting a sleep or yield in the loop would help though better solutions exist i.e. really this thread should be waiting for a signal/ joining whatever.

Have a look at Java 7's fork / join for instance ...




I agree that this is not a right approach that's why I had to post it here to get a proper solution.
Can you change/optimize the code to show what I could do so that I get desired output.

Vijitha Kumara wrote:Welcome to CodeRanch, Rony Dsouza!

I would like to know if there is a way where in i could write the result to file when both the threads finished their work?
Also the main method/thread finshes before the other threads are done processing can I make the main thread wait till other threads finish execution?


You have to make the main thread waiting for those two threads... Then you can continue the main thread. There can be few options on how to implement this. Can you show us how you have implemented it so far?



Thanks Vijitha. Below is what I have done till now. This is a sample code that I am using.
As of now I have created a third thread and making it wait till complete count is 2 before it prints the file. It works most of the times but sometimes it stays in the while loop for a long time. I am new to java so may be I am taking the wrong approach.

I have create a thread pool which creates two threads at a time. My program breakes a arraylist into two sublists and then each thread iterates over one list & adds result to a syncronized set and finally I create another thred to write the contents the sync set to a text file.
The problem is whenver one of the two list iterator thread finishes the write to file thread runs and prints incomplete output to a file.
I would like to know if there is a way where in i could write the result to file when both the threads finished their work?
Also the main method/thread finshes before the other threads are done processing can I make the main thread wait till other threads finish execution?