Bookmark Topic Watch 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator








run() is called:


What to look for: notice the order the Threads run in. Without being "forced" to sleep, the Threads will not necessarily take turns. If you can run this applet on both a Macintosh and a PC, you might see a DRASTIC difference. On a PC, thread scheduling often works the way you might hope: the Threads appear to take turns, more or less. But on a Macintosh, one Thread might just stay in until it has finished!

WARNING: turn-taking is NOT built into Java! The responsibility is for you, the programmer. So while you might get good behavior on a PC, you can't guarantee it across all Java platforms. To guarantee fair Thread behavior (proper turn-taking) you must use a strategy which employs yield() and/or sleep(). So if this NoSleep example runs on your machine exactly like the ThreadTwo example (which DOES sleep), you're lucky. Nothing programmed in the Java applet is making that happen.

Bottom Line: If you're just starting with Threads, ALWAYS USE SLEEP in your run() method to be safe. Later, as you become more experienced with Threads you may use more sophisticated scheduling strategies.



CODE






CodeBarnApplets
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic