• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

displaying static int

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic