How to call a method with a separate thread in Java?

Louis Rhys picture Louis Rhys · Aug 16, 2010 · Viewed 279.2k times · Source

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

Answer

MANN picture MANN · Feb 5, 2014
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();
    }
});