• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads  RSS feed

 
Nelson Nadal
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My thread foundation is still a little bit shaky, so I want to ask help from you.
I just want to make 2 thread that performs different function. One is showing diff. characters, the other one is counting up to 1 billion and shows "One Billion".
The idea is I want to show the diff. characters while the other one is counting up to 1 billion. After reaching the 1 billion it shows text "One Billion" the other threads showing diff. characters shld also stop.
I made two programs, 1 is not producing right result and the other 1 is right, I just want to know why the other 1 is not working since that is the one I think is more right? Or what's the best code? Thanks.

Program 1 (wrong result, its just shows "One Billion" not showing chars)


Program 2. (OK)
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second program is not only correct, it's also correct...
Remember that "start()" returns right away; it doesn't wait around for the thread to execute. So in your first program, the character thread gets interrupted before it even gets started -- the line "c.interrupt()" is likely to execute before the first character is printed.
The second one does exactly what you want: the billion thread communicates with the char thread using the interrupt() method. This is quite good style.
If you're worrying about the two threads being coupled, then there are definitely alternatives: the billion thread could send an event, or notify an Observable, or something, and the char thread could be listening for events, or be an Observer... but in any case, these schemes wouldn't change what's fundamentally going on.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to the Threads forum.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!