Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java; Diffrence between making Thread

I just today started to learn Threads in Java. So far I have seen people usually use 2 methods to create them, but I don't understand the difference between them:

1:

new Thread() {
    @Override
    public void run(){
        //mycode goes here;
    };
}.start();

2:

new Thread(new Runnable() {
    @Override
    public void run(){
        //mycode goes here;
    }
}).start();

So why does people use new Runnable(), if that's not necessary? It just forces you to have run() method, but if you create thread then its not logical to not create run method yourself? Or am I wrong?

But why to use new Runnable() when creating anonymous Threads? Like in second example above? Since I have seen that is some tuturials, which I found online. I am just asking if there is a reason of doing it or not.

I know that Thread can be created also in other ways:
(And I am not speaking about implementing vs extending!)

3:

Thread t1 = new Thread(new MyRunnable());

4:

MyThreadClass my1 = new MyThreadClass();
like image 257
arccuks Avatar asked Nov 19 '25 13:11

arccuks


1 Answers

It might be useful in some situations when you already have an instance of Runnable to just run in in a different Thread. For example Runnables can be used for excapsulating the Command Design Pattern.

In your case there is no reason to create Runnable as it does not add anything.

like image 102
Crazyjavahacking Avatar answered Nov 22 '25 04:11

Crazyjavahacking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!