views:

218

answers:

2

let's say I have a method doWork(). How do I call it from a separate thread (not the main thread).

+12  A: 

Create 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.

Noel M
what if there is a variable you would like to pass?
Louis Rhys
The `run()` method takes no parameters, so you can't pass a variable there. I'd suggest that you pass it in the constructor - I'll edit my answer to show that.
Noel M
+2  A: 

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.

raja kolluru
Future and Callable do this kind of thing for you.
Amir Afghani
Yep they do. the idea here is to abstract the interface behind an asynchronous wrapper.
raja kolluru