views:

627

answers:

5

Hi everyone, I'm new to this site and glad to be here :).

I'm not a good java programmer, it's just my hobby, but I'm eager to know more than average stuff.

I want to solve a mathematical problem with multiple threads in java. my math problem can be separated into work units, that I want to have solved in several threads.

but I don't want to have a fixed amount of threads working on it, but instead a coresponding amount of threads to the amount of cpu cores. and my problem is, that I couldn't find an easy tutorial in the internet for this. all I found are examples with fixed threads.

So could you help me with a link to a good tuturial or could give me an easy and good example? That would be really nice :)

thank you in advance,

Andreas

+3  A: 

On the Runtime class, there is a method called availableProcessors(). You can use that to figure out how many CPUs you have. Since your program is CPU bound, you would probably want to have (at most) one thread per available CPU.

Eric Petroelje
Hi Jason and Eric (I use one comment for both of your answers, because it's basicly the same).okay, that's nice to check, but this would be the first part. When I have the core count I have to have the threads as variable as this amount of cores.I tried this example before http://openbook.galileodesign.de/javainsel5/javainsel09_003.htm#Rxx747java09003040002E31F0491F9 (German!) and it uses a fixed thread. But I want to have the same programming using 2 core in a dual-core environment, and 4 cores in a quad-core environment. I don't want to change it manually.Is this possible?THX! :)
Andreas Hornig
@Andreas - See the updates I made to my post. I think that will help clarify the issue.
JasCav
+12  A: 

You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, availableProcessors. Once you have determined the number of processors available, create that number of threads and split up your work accordingly.

Update: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object. So, let's say that you call the above method and find that it returns 2 processors. Awesome. Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread. Here's some psuedocode to demonstrate what I mean:

int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
  Thread yourThread = new AThreadYouCreated();
  // You may need to pass in parameters depending on what work you are doing and how you setup your thread.
  yourThread.start();
}

For more information on creating your own thread, head to this tutorial. Also, you may want to look at Thread Pooling for the creation of the threads.

JasCav
This is basically correct, but be careful about performance on processors marketed with Intel's "hyper-threading". On a quad-core, this will return 8 instead of 4, but your performance may actually start dropping after 4 threads - so my own benchmarks tell me :)
xcut
Hi,okay, didn't know, that this is possible.but when I split one task into several workunits and I need all part solution for the final workstep, how is this done? When I have several "yourThreads" how to I use join() for this, because I don't see, how these several threads are distinguishable?:)BTW: your link to Thread Pooling lead me to http://www.ibm.com/developerworks/library/j-jtp0730.html :)
Andreas Hornig
Look at the example here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html It will tell you a more streamlined way to create and manage the thread pool... It may seem more complicated at first, but as with most things, it's more complicated because if it was simpler you'd just hit limitations sooner.
Bill K
+9  A: 

You probably want to look at the java.util.concurrent framework for this stuff too. Something like:

ExecutorService e = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// Do work using something like either
e.execute(new Runnable() {
        public void run() {
            // do one task
        }
    });

or

    Future<String> future = pool.submit(new Callable<String>() {
        public String call() throws Exception {
            return null;
        }
    });
    future.get();  // Will block till result available

This is a lot nicer than coping with your own thread pools etc.

DaveC
Hi DaveC,hmmm, haven't known that before, so I will have a look at this. And it can be scaled according to available cpu cores? Because I can't see that in you short examples.Best regards, Andreas
Andreas Hornig
java.util.concurrent is highly scalable
Kristopher Ives
A fixed size pool with the number of available processors is often optimal for CPU bound processes. The first example here is all you need to do.
Peter Lawrey
A: 

Doug Lea (author of the concurrent package) has this paper which may be relevant: http://gee.cs.oswego.edu/dl/papers/fj.pdf

David Soroko
A: 

Hi again,

thanks to Jason and the rest of you, I did this

but I don't like my way in joining them. is there a more elegant way in doing this?

Andreas

public class Main {
static class JoinerThread extends Thread
  {
    public int id;
    public int result;
    @Override
public void run()
{
    for(int i=0; i<999999999; i++){
        Math.pow(i,2);
    }

    result = id;
}
  }
  public static void main( String[] args ) throws InterruptedException
  {
int processors = 3;
JoinerThread threads [] = new JoinerThread[processors];
for(int i=0;i<processors;i++){
    threads[i] = new JoinerThread();
    threads[i].id = i;
    threads[i].start();
}
for(int i=0;i<processors;i++){
    threads[i].join();
    System.out.println("gnaa");
}

for(int i=0;i<processors; i++){
    System.out.println( threads[i].result );
}
  }
}
Andreas Hornig