Louis Rhys Louis Rhys - 1 year ago 125
Java Question

How to call a method with a separate thread in Java?

let's say I have a method

. How do I call it from a separate thread (not the main thread).

Answer Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download