This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Linux and Java Threading

 
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 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) {
}
}
}
}
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK I realized a value of 100 in the loop was too small for the scheduler to switch between threads!
 
Tim Holloway
Saloon Keeper
Posts: 18303
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic