You cannot directly call methods on a Thread object. The only way to get concurrency with a Thread is to invoke its start() method, which in turn calls run() on a separate thread of execution. Calling any other methods directly from main() is just like calling methods on regular non-Thread objects; there's no concurrency, nothing special happens, the methods execute immediately.
It sounds like you're trying to communicate between the main thread and the worker threads. Each thread's run() method is in charge of executing code on that thread. If you can communicate with that run() method then you can control what happens on that thread.
One way to do that is to pass a variable in when you construct the Thread. Save a value that the run() method can examine to determine what to do. For example, below we have an enum that has three possible actions in it. The run() method looks at the enum and decides what to do based on the value that was passed to the WorkerThread() constructor.
class WorkerThread {
public enum Action { DO_STUFF, MAKE_WIDGETS, FROB_BARS }
private Action action;
public WorkerThread(Action action) {
this.action = action;
}
public void run (){
switch (action) {
case DO_STUFF: doStuff(); break;
case MAKE_WIDGETS: makeWidgets(); break;
case FROB_BARS: frobBars(); break;
}
}
public void doStuff() { ... }
public void makeWidgets() { ... }
public void frobBars() { ... }
}
Now our main() method looks like this. You create WorkerThreads passing in the action to perform, then call start().
WorkerThread[] threads = new WorkerThread[10];
for (int i = 0; i < threads.length; ++i) {
threads[i] = new WorkerThread(WorkerThread.Action.DO_STUFF);
threads[i].start();
}
You could do the same thing in myriad different ways. Instead of having one WorkerThread class you could have several different classes with differing run() methods and then instantiate the appropriate sub-class from main().
class DoStuffWorkerThread extends Thread { ... }
class MakeWidgetsWorkerThread extends Thread { ... }
class FrobBarsWorkerThread extends Thread { ... }
You can even create anonymous Thread classes right inside main(), if you like. Then the logic can be whatever main() wants.
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; ++i) {
threads[i] = new Thread() {
public void run() {
doStuff();
}
};
threads[i].start();
}
Runnables insidemain, but why?