let's say I have a method doWork()
. How do I call it from a separate thread (not the main thread).
views:
218answers:
2Create a class that implements the Runnable
interface. Put the code you want to run in the run()
method - that's the method that you must write to comply to the Runnable
interface. In your "main" thread, create a new Thread
class, passing the constructor an instance of your Runnable
, then call start()
on it. start
tells the JVM to do the magic to create a new thread, and then call your run
method in that new thread.
public class MyRunnable implements Runnable {
private int var;
public MyRunnable(int var) {
this.var = var;
}
public void run() {
// code in the other thread, can reference "var" variable
}
}
public class MainThreadClass {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable(10);
Thread t = new Thread(myRunnable)
t.start();
}
}
Take a look at Java's concurrency tutorial to get started.
If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future
, Callable
, Executor
classes in the java.util.concurrent
package.
Sometime ago, I had written a simple utility class that uses JDK5 executor service and executes specific processes in the background. Since doWork() typically would have a void return value, you may want to use this utility class to execute it in the background.
See this article where I had documented this utility.