Java; Difference between creating Thread
I just started learning Java topics today. So far I've 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 do people use new Runnable()
it if they don't need it? It just forces you to have a method run()
, but if you are creating a thread, then wouldn't it be logical not to create a start method yourself? Or am I wrong?
But why use it new Runnable()
when creating anonymous streams? Like the second example above? As I saw that these are some tutorials I found on the internet. I'm just asking if there is a reason to do this or not.
I know that Thread can be created in other ways as well:
(And I'm not talking about implementing a vs extension!)
3
Thread t1 = new Thread(new MyRunnable());
4
MyThreadClass my1 = new MyThreadClass();
source to share
Basically, you need to understand that if you need to change the behavior of a Thread, then you need to extend the Thread class, otherwise, if you just need to run separate threads, then you need to implement the Runnable interface.
See more here: fooobar.com/questions/944733 / ...
source to share