How to call a method with a separate thread in Java?
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();
}
});
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.
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();
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();