185

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

3

8 Answers 8

279
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        // code goes here.
    }
});  
t1.start();

or

new Thread(new Runnable() {
     @Override
     public void run() {
          // code goes here.
     }
}).start();

or

new Thread(() -> {
    // code goes here.
}).start();

or

Executors.newSingleThreadExecutor().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

or

Executors.newCachedThreadPool().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});
7
  • 1
    This worked perfectly for what I was doing. Needed to run a webservice and updating a progress bar concurrently using the observer pattern.
    – dpi
    Commented Feb 15, 2014 at 15:20
  • @Ashish: Please explain what and why has been edited?
    – MANN
    Commented Oct 30, 2014 at 14:55
  • @MANN can you explain why you use run method in Thread parameter? any better performance? Commented Oct 5, 2015 at 14:32
  • 6
    Do we need to explicitly terminate the thread? Isn't there a risk of creating a memory leak by not explicitly terminating the thread? Or does the thread terminate when it's done with run()?
    – theyuv
    Commented Apr 15, 2016 at 18:59
  • 3
    In Java 8 and later we can replace new Runnable() {...} verbose stuff with () -> myCustomMethod() Commented Oct 16, 2019 at 23:05
162

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.

5
  • 1
    what if there is a variable you would like to pass?
    – Louis Rhys
    Commented Aug 16, 2010 at 7:21
  • 10
    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
    Commented Aug 16, 2010 at 8:15
  • 1
    Is there a short way for calling 1 method in a different thread? I know of the new Thread() { public void run() {myMethod();}}.start(); way, is that the shortest? Commented Nov 29, 2012 at 22:38
  • @NoelM can you explain difference between yours and MANN's answer? Commented Oct 5, 2015 at 14:40
  • 2
    MANN's answer uses an anonymous implementation of Runnable - mine is a class that extends Runnable. And because I've done that I have my own constructor which passes state into the instantiated object.
    – Noel M
    Commented Oct 6, 2015 at 8:28
79

In Java 8 you can do this with one line of code.

If your method doesn't take any parameters, you can use a method reference:

new Thread(MyClass::doWork).start();

Otherwise, you can call the method in a lambda expression:

new Thread(() -> doWork(someParam)).start();
5
  • sorry to bring this back but what exactly does the -> mean?
    – Kyle
    Commented Aug 25, 2015 at 13:50
  • 2
    That is the syntax used to create a lambda expression. Take a look at these links for more info: What does '->' do in Java?, and The Java™ Tutorials - Lambda Expressions
    – Aaron Cohn
    Commented Aug 25, 2015 at 19:38
  • @AaronCohn great stuff man! Do you know any alternatives to threads in Java? I come from the Python world, whre we would use Celery task queue for for asynchronous stuff
    – CESCO
    Commented Nov 5, 2015 at 18:10
  • Java has higher level abstractions for dealing with Threads, but maybe you're looking for something more like Akka?
    – Aaron Cohn
    Commented Nov 6, 2015 at 18:52
  • My method throws exception. How can I throw an exception from a thread in your first example?
    – Hrvoje T
    Commented Mar 11, 2022 at 15:22
20

If you are using at least Java 8 you can use method runAsync from class CompletableFuture

CompletableFuture.runAsync(() -> {...});

If you need to return a result use supplyAsync instead

CompletableFuture.supplyAsync(() -> 1);
8

Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression

  new Thread(() -> {
                      "code here"
            }).start();
1
  • 1
    Can you please explain a little about the lifecycle of the thread created above ?
    – himanshu
    Commented Feb 6, 2023 at 8:21
4

To achieve this with RxJava 2.x you can use:

Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();

The subscribeOn() method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io() which has a thread pool intended for I/O operations, and Schedulers.computation() which is intended for CPU intensive operations.

2

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.

4
  • 7
    Future and Callable do this kind of thing for you. Commented Aug 15, 2010 at 23:46
  • Yep they do. the idea here is to abstract the interface behind an asynchronous wrapper. Commented Aug 16, 2010 at 14:44
  • The link is broken (404).
    – palacsint
    Commented Sep 12, 2019 at 21:05
  • 1
    @palacsint I changed the link. Now it will work. sorry about that Commented Aug 28, 2021 at 9:15
0

In java 8 you can call it through method reference by creating new thread.

Thread t = new Thread(new YourClassName::doWork);
t.start();

you can refer static mathod also, in that case you don't need to use new operator.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 26, 2023 at 9:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.