File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Linux / UNIX and the fly likes Linux and Java Threading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » Linux / UNIX
Bookmark "Linux and Java Threading" Watch "Linux and Java Threading" New topic
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: 16303
    
  21

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.


Customer surveys are for companies who didn't pay proper attention to begin with.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Linux and Java Threading