In Java, I know that the default thread priority is 5. I have a class which basically sleeps for n number of seconds while doing other stuff on the side. If I create 20 threads in random order, each with that class as the target with n being either 10 or 20 seconds, how is it that all the 10 second ones finish first, and then the 20 second ones finish.
What I thought would happen was that since I am running a dual core processor, only 2 threads can run actually simultaneously. Therefore, the scheduler would pick 2 threads arbitrarily, since they are all the same priority, and run them first, which means that sometimes a 20 second thread will have to run before a 10 second one and so on and so forth.
I would assume this is because the quanta for the threads is much smaller than their run time of 10 or 20 seconds when they are scheduled. Even if a 20s thread gets into the run queue first, it will not actually run to completion all at once. It will get bumped back out to the wait queue by the thread scheduler after its time slice runs out, which is probably a comparatively short amount of time.
See here for a pretty good article on thread scheduling algorithms. The basic summary is that each thread will run for some small amount of time (on the order of milliseconds perhaps), then it will get swapped out for another thread. This thread swapping will continue until all threads are finished.
Additionally, the Wikipedia entry on scheduling is pretty good. Although some of it specifically refers to process scheduling, modern OSes generally deal with threads in the same manner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With