• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Linux and Java Threading

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Saloon Keeper
Posts: 27763
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic