| Author |
Linux and Java Threading
|
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 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) { } } } }
|
<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
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
|
OK I realized a value of 100 in the loop was too small for the scheduler to switch between threads!
|
 |
Tim Holloway
Saloon Keeper
Joined: Jun 25, 2001
Posts: 12513
|
|
Actually, there are 2 different threading options in Java. One is named "green threads" and I don't know if the other has a name at all. The difference is that one runs pre-emptive multitasking and the other runs co-operative (or so I understand). The co-operative model is designed for environments that cannot run pre-emptive. You can find out more threading in the JavaRanch multi-threading forum.
|
One of the most odious afflictions that Business has inflicted on the modern English language is "pro-active". Most of the time it's simply redundantly used in place of the simple old word "active". And a good deal of the rest of the time it means "You're not overworked enough yet, so go out and find more!"
|
 |
 |
|
|
subject: Linux and Java Threading
|
|
|