Best way of creating and using an anonymous Runnable class Best way of creating and using an anonymous Runnable class java java

Best way of creating and using an anonymous Runnable class


No, you usually won't call run() directly on a Runnable as you will get no background threading that way. If you don't want and need a background thread, then fine call run() directly, but otherwise if you want to create a background thread and run your Runnable from within it, you must create a new Thread and then pass in the Runnable into its constructor, and call start().

Also, there are other ways of accomplishing this task including use of Executors and ExecutorServices, and you should look into the uses of this as they offer more flexibility and power than using a bare bones Thread object.

Also you'll want to have a look at use of the Future interface and the FutureTasks class that are like Runnables only they allow you to return a result when complete. If you've used a SwingWorker, then you've already used a Future interface without realizing it.


As the others have mentioned, using the Thread class is the correct way. However, you should also look in to using Javas Executors framework to handle running threads.

Executors.newSingleThreadExecutor().execute(new Runnable() {    @Override     public void run() {        // code in here    }});

Of course, just using Thread directly is fine. But it is generally advised (or preferred) to use the framework. Let Java handle the fine details for you.


The Runnable interface must be executed inside a Thread. If you want to find another way to wrap inline, a chunk of code inside a Thread, try:

Thread t = new Thread(){     public void run()     {        // put whatever code you want to run inside the thread here.     }};t.start();