Easy way to call method in new thread Easy way to call method in new thread multithreading multithreading

Easy way to call method in new thread


Since Java 8 you can use shorter form:

new Thread(() -> {    // Insert some method call here.}).start();

Update:Also, you could use method reference:

class Example {    public static void main(String[] args){        new Thread(Example::someMethod).start();    }    public static void someMethod(){        // Insert some code here    }}

You are able to use it when your argument list is the same as in required @FunctionalInterface, e.g. Runnable or Callable.

Update 2:I strongly recommend utilizing java.util.concurrent.Executors#newSingleThreadExecutor() for executing fire-and-forget tasks.

Example:

Executors    .newSingleThreadExecutor()    .submit(Example::someMethod);

See more: Platform.runLater and Task in JavaFX, Method References.


Firstly, I would recommend looking at the Java Thread Documentation.

With a Thread, you can pass in an interface type called a Runnable. The documentation can be found here. A runnable is an object that has a run method. When you start a thread, it will call whatever code is in the run method of this runnable object. For example:

Thread t = new Thread(new Runnable() {         @Override         public void run() {              // Insert some method call here.         }});

Now, what this means is when you call t.start(), it will run whatever code you need it to without lagging the main thread. This is called an Asynchronous method call, which means that it runs in parallel to any other thread you have open, like your main thread. :)


In Java 8 if there is no parameters required you can use:

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

Or in case of parameters:

new Thread(() -> doWork(someParam))