EvilZone
Programming and Scripting => Java => : Matriplex March 27, 2014, 10:27:39 PM
-
So I've actually wondered this for quite a while, but I've never really asked anyone.
When learning how to use multiple threads in Java a few years ago I set up a test to see how a thread would print out compared to another thread. All I did was make a quick loop that looked something like this:
//pseudo code
private int start = 0, end = 200;
public void loop() {
while (true) {
if (start >= end) {
start = 0;
System.out.println("Thread 1"); //Or 2, there was one for the other thread class
} else {
start++;
}
}
}
So, very simple code you should understand even if you don't code in java :)
They seemed to print out "Thread X" somewhat randomely. I get the same results in Python as well.
Is there any particular reason for this, or is it just because each thread is in a queue of some sort?
Thanks
-
So, both threads increment `start' to 200, then reset it to 0. No one know, which thread will run if-true clause, it may be one thread or another, just a matter of case.
-
Is there any particular reason for this
Yes: https://en.wikipedia.org/wiki/Scheduling_%28computing%29
Especially:
In computer science, scheduling is the method by which threads, processes or data flows are given access to system resources (e.g. processor time, communications bandwidth). This is usually done to load balance and share system resources effectively or achieve a target quality of service.
If you write multithreaded programs you have no control over the actual order the processes are run. That's what the scheduler does based on throughput, latency, fairness and waiting time.