This week's book giveaway is in the HTML/CSS/JavaScript forum.
We're giving away four copies of Practical SVG and have Chris Coyier on-line!
See this thread for details.
Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

displaying static int

 
Ian Cockcroft
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, i am runnning a few threads, each one counts from 1-100,101-200,201-300 etc. each thread looks for prime numbers in their respective range. When one is found, it updates a static int countPrime. I then want to display prime. If I put it in main, it displays before any threads have run and is there for 0. where and how should I display it?
Thanks Ian
 
Alain Boucher
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do not use a Static int variable. Use a vector, in your thread constructor, pass the vector to your thread, when the thread found a prime number, add it to the Vector (as String) and make the thread print that number to the System.out To be more nice, make your thread constructor method taking a OutputStream and pass the System.out as argument.
In that way, your prime number will be display where ever your want and you will have the prime number in a vector for further use
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what the real purpose is here - seems like this is a fairly inefficient way to look for primes, so I'll assume this is for educational purposes, and searching for primes is just a token example of "work" for a thread to be occupied with. So, ignoring issues like "why would you use threads for this"...
If you want to display results after all the prime-seeking threads have completed, you need to write a loop that explicitly waits for them all. Let's say you've got all the Threads you're waiting for in an array named "threads":

Here we wait for each thread in turn, using join(). In many cases, the thread may have already completed while we were waiting for another thread - in which case join() will return immediately, and the loop will go on to the next thread. When the loop has completed, we will be certain that all threads in the array have completed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!