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();
This can be useful in some situations where you already have an instance Runnable
to run on just a different thread. For example, Runnable
it can be used to dig out a command design pattern.
In your case, there is no reason to create Runnable
as it adds nothing.
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 / ...
You may have heard of thread pools where we reuse threads to process different jobs (read runnables). Have a look at the threadpoolexecutor API dispatch method. This will give you some idea.