Creating dirty methods for threads in Java
I recently started to delve into multithreading in Java In the process of exploring things, I found that there are two fast and dirty ways in Java to create threads "anytime, anywhere" Here is an example:
public static void main(String[] args) {
System.out.println("Thread: " + Thread.currentThread().getName());
new Thread() {
public void run() {
System.out.println("Thread: "
+ Thread.currentThread().getName());
System.out.println("hello");
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread: "
+ Thread.currentThread().getName());
System.out.println("hello");
}
}).start();
}
>The first one is the one that starts with the new thread () > the second one appears after the one that starts with the new thread (the new runnable()){
I just want to ask whether the two methods are correct? In addition to implementing the runnable interface V / s extension thread class, what are the differences?
Solution
Both methods are acceptable (in my opinion, neither of them is "dirty") The first is not so lengthy, and I like such a small thing like this If you are extending thread, you can also skip thread currentThread():
new Thread() {
public void run() {
System.out.println("Thread: " + getName());
System.out.println("hello");
}
}.start();
However, in any nontrivial case (i.e. if the thread is more than a few prints), the usual "favor composition over inheritance" rule applies to the second method
If you are using java 8, you can even use runnable as a functional interface:
new Thread(() -> {
System.out.println("Thread: " + Thread.currentThread().getName());
System.out.println("hello");
}).start()
One last thing: I rarely use threads these days Whenever I do this, I tend to end up rewriting it using executorservices
