I’m writing a Java application that uses some threads. Main method looks like this:
WorkerThread[] thread = new WorkerThread();
for (int i = 0 ; i<10 ; i++) {
thread = new WorkerThread();
thread.doStuff();
}
and my WorkerThread looks like this:
class WorkerThread {
public void run() {
...
}
public void doStuff() {
...
}
}
The matter is that, obviousely, I call doStuff from the run method it is executed like concurrently with other threads, but if i call doStuff directly from the main it is executid not cocurrently.
Ok, now the question is: is there a way to execute, concurrently, the doStuff method calling it not from the run method, but rather, from the main?
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.
Now our main() method looks like this. You create WorkerThreads passing in the action to perform, then call 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().
You can even create anonymous Thread classes right inside main(), if you like. Then the logic can be whatever main() wants.