aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Shouldnt the output overlap?(Threading) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Shouldnt the output overlap?(Threading)" Watch "Shouldnt the output overlap?(Threading)" New topic
Author

Shouldnt the output overlap?(Threading)

Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361

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

Joined: Feb 07, 2005
Posts: 643

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

Joined: Mar 04, 2006
Posts: 361
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

Joined: Aug 24, 2005
Posts: 518
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Shouldnt the output overlap?(Threading)