Forums Register Login

Shouldnt the output overlap?(Threading)

+Pie Number of slices to send: Send

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??
+Pie Number of slices to send: Send

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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
 

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.
What a show! What atmosphere! What fun! What a tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 716 times.
Similar Threads
Runnable to Thread Casting
Threads
CertPal #33 on Threads
Exercise 13.6 in - A Programmer's Guide to Java SCJP Certification - 3rd Ed
Threads
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 02:49:28.