Create a class that implements the Runnable interface. Put the code you want to run in the run() method, the method you must write to fit the Runnable interface. In your main thread, create a new Thread class by passing an instance of your Runnable constructor, and then call start() on it. start tells the JVM to do the magic to create a new thread, and then calls your run method on that new thread.
public class MyRunnable implements Runnable { private int var; public MyRunnable(int var) { this.var = var; } public void run() {
Check out the Java concurrency tutorial to get started.
If your method will be called frequently, then it may not be worth creating a new thread every time, as this is an expensive operation. It is probably best to use a thread pool. Check out the Future , Callable , Executor classes in the java.util.concurrent package.
Noel M Aug 15 2018-10-18T00: 00
source share