let's say I have a method doWork()
. How do I call it from a separate thread (not the main thread).
-
There happen to be some examples over on this recent related question: killing an infinite loop in java– Greg HewgillCommented Aug 15, 2010 at 22:41
-
stackoverflow.com/questions/36832094/… I have a similar issue pls help me to solve this– Sruthi AcgCommented Apr 25, 2016 at 5:31
-
You may also like to take a look at Reactive Java blog.danlew.net/2014/09/15/grokking-rxjava-part-1 for asynchronous tasks– Nathan DunnCommented Jan 6, 2017 at 1:31
8 Answers
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();
}
});
-
1This worked perfectly for what I was doing. Needed to run a webservice and updating a progress bar concurrently using the observer pattern.– dpiCommented Feb 15, 2014 at 15:20
-
-
@MANN can you explain why you use run method in Thread parameter? any better performance? Commented Oct 5, 2015 at 14:32
-
6Do 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()
?– theyuvCommented Apr 15, 2016 at 18:59 -
3In Java 8 and later we can replace
new Runnable() {...}
verbose stuff with() -> myCustomMethod()
Commented Oct 16, 2019 at 23:05
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.
-
1
-
10The
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 MCommented Aug 16, 2010 at 8:15 -
1Is 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
-
2MANN's answer uses an anonymous implementation of
Runnable
- mine is a class that extendsRunnable
. And because I've done that I have my own constructor which passes state into the instantiated object.– Noel MCommented Oct 6, 2015 at 8:28
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();
-
-
2That 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 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– CESCOCommented 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? 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 TCommented Mar 11, 2022 at 15:22
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);
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();
-
1Can you please explain a little about the lifecycle of the thread created above ?– himanshuCommented Feb 6, 2023 at 8:21
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.
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.
-
7
-
Yep they do. the idea here is to abstract the interface behind an asynchronous wrapper. Commented Aug 16, 2010 at 14:44
-
-
1@palacsint I changed the link. Now it will work. sorry about that Commented Aug 28, 2021 at 9:15
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.
-
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 BotCommented Jan 26, 2023 at 9:37