I just found out that
java uses a pre-emptive threading model in Linux, therefore when I create a simple app with two threads to output a few line from a for loop. What I am seeing is that one
thread hogs the CPU until completion, and then the 2nd thread is allowed to run.
I've tried putting a yield() within the loop, but this doesn't do anything useful, but by putting a sleep(0) I found I can achieve a threading model which is more true to a time-slicing model, the down side is the programs run slower because of the context switching that takes place.
Has anyone found a better solution for this problem?
Here is my modified code: (remove the try/catch block to see the problem)
class
Test {
public static void main(
String[] arg) {
Runner one = new Runner("One");
Runner two = new Runner("Two");
one.start();
two.start();
}
}
class Runner extends Thread {
String strName;
Runner(String str) {
strName=str;
}
public void run() {
for(int i=0; i<100; ++i) {
System.out.print(strName);
try {
sleep(0);
}catch(InterruptedException e) {
}
}
}
}