This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shouldnt the output overlap?(Threading)

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In the above I have made 2 instances of the inner class Run1 and handed them to the 2 respective threads. The o/p is a clean: 0,1,2,3,4 0,1,2,3,4. But there are two objects of Run1 class, which means there are also two sets of run methods, and each thread is executing a different run method, why arent the results overlapping??
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i have made some changes to your code.
Run above code and see overlapped output.
If above code does not show overlapped output
increase loop number at line 4 you will get overlapped output.
 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah i get that if you increase the iteration count the output begins to overlap but my question is If I have two objects each object with its own copy of run and each object has 1 thread executing its run, shouldnt the output begin overlapping from the get go. Or is there only 1 thread scheduler for as many objects as one can make with diff threads? I reckon
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shouldnt the output begin overlapping from the get go


Not necessarily. Just because a thread is "runnable" doesn't mean it's "running." The scheduler decides which of the runnable threads should be running.

In your case, with a small number of iterations, the scheduler is starting one thread and it finishes the small number of iterations before the scheduler preempts it.

By increasing the iteration count, the thread runs long enough to be preempted in favor of another thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic