Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Linux and Java Threads

 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic