views:

78

answers:

4

Hey Guys,

I've got a class which starts a new thread by calling

public void omnom(){
   t = new Thread(this, "My Thread"); 
   t.start();
}

The new thread then runs inside the run() method. So I have two threads working fine but how would I add a third? I'd like to "split" off 2 threads e.g t.start(); + f.start(); how would I split off both of them from omnom() and send them to 2 different "run()" methods?

Thanks!

+2  A: 

You could create an anonymous Runnable class to call whatever "run" method you prefer:

public void omnom() {
    new Thread(this, "My Thread").start();
    new Thread(
            new Runnable() {
                public void run() {
                    otherRunMethod();
                }
            }
        ).start();
}
Adam Paynter
A: 

By simply repeating the new Thread() and the start().

You must distinguish between compile-time structure and runtime structure. You can have as many threads using the same class byte code as you want, and they will happily execute whatever part of the class is in order for their private execution flow - even if it is the same line of code currently executed by another thread!

(In fact, that is the entire reason why concurrent programming is so complex, and why synchronisation is even needed: because the bytecode is not owned by a particular thread, but by a classloader.)

Kilian Foth
+1  A: 

When you create the thread, you're passing in an instance of Runnable as the first parameter - and its this runnable's run() method that gets invoked by the thread.

So in your specific case, you're passing in this - presumably the class you're calling from implements Runnable and has a run() method, which is why that method gets invoked by thread t. To have another thread f call another method, you'll simply need to pass a different instance of Runnable into the thread's constructor that has the different run() method, something like this:

public void omnom(){
   Thread t = new Thread(this, "My Thread"); 
   t.start();

   // Get this Runnable from somewhere, possibly pass it in as a method
   // parameter/construct it explicitly here/whatever
   Runnable fRunner = ...;
   Thread f = new Thread(fRunner, "My Other Thread");
   f.start();
}
Andrzej Doyle
A: 

I don't have enough karma to up vote but Adam Paynter's advice is what you want.

bradgonesurfing