Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of creating and using an anonymous Runnable class

I want to use an anonymous class for Runnable. There are two ways, but I don't know if they do the same thing or not:

Method one: using Runnable directly and then calling run():

new Runnable() {     @Override     public void run() {     } }.run(); 

Method two: create an anonymous Runnable and paste to Thread, using the start() method instead of run():

new Thread(new Runnable() {     @Override     public void run() {     } }).start(); 

I think method two is obviously true. But, I don't know if it does the same thing as method one. Can we call the run() method on a Runnable directly?

like image 670
hqt Avatar asked Oct 07 '12 18:10

hqt


People also ask

How do I create a runnable class?

Create A Runnable Class (Job) First, open Visual Studio and Create a new solution and project. Secondly, right click on the project, and select Add>New Item. Thirdly, select Dynamics 365 Items, on the left, and then select 'Runnable Class (Job)' from the list. Fourthly, enter in a name.

How do I create an anonymous class in Java 8?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.


2 Answers

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.

like image 65
Hovercraft Full Of Eels Avatar answered Oct 06 '22 02:10

Hovercraft Full Of Eels


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.

like image 21
jakson Avatar answered Oct 06 '22 02:10

jakson