| Author |
Linux and Java Threads
|
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
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 lines 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 on a Linux box) 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) { } } } } [ January 18, 2002: Message edited by: Rajinder Yadav ]
|
<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
|
 |
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
|
|
How much time did you give each thread? I mean, how many iterations in your loop? Are you sure that the first thread maybe just got enough running time to complete it's loop before the scheduler switched it over? What happens when you try two threads, each printing a different message, each in an infinite loop? Sorry I can't be helpful at the moment but maybe you can post your original code and I can look at that? Rob
|
Rob
SCJP 1.4
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
Rob, thanks for making me check. I tried a loop value of 10000, and removed the sleep(0) call and it seems the two threads are getting the time-slice. BTW, the original code was: 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<10000; ++i) { System.out.print(strName); } } } [ January 18, 2002: Message edited by: Rajinder Yadav ]
|
 |
 |
|
|
subject: Linux and Java Threads
|
|
|