Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scenario where extending thread is preferred than implement Runnable? [duplicate]

As a beginner, I was reading about 2 ways of implementing Multithreading in Java.

I read this thread on SO and on many other threads.

It is stated that

"prefer runnable" , extends thread only when you are specialising Thread's behaviour.

Can someone explain me what is meant by specializing Thread behaviour by providing me a small piece of snippet which help me understand this line.

like image 647
Raj Avatar asked Mar 18 '14 09:03

Raj


2 Answers

You should extend a Thread as much as you extend other library classes.

Take a List for example, more specifically ArrayList, you could add extra behaviour on it, like rejecting a value when adding if a certain predicate fails.
Then you can call that an PredicatedArrayList.

It is still a debate whether you want to extend ArrayList here or not, but that debate is not up for this question.

So an example of extending a thread would be a thread that kills itself after a specific amount of time. Then you would have SuicidingThread extends Thread, which could have a constructor taking the time.

This even fortifies the argument that you should put your actual tasks in a Runnable.
Like Runnable somethingRunnable = new SomeClass();, where SomeClass implements Runnable.

Now you can do either:

  • Thread someThread = new Thread(somethingRunnable);
  • Thread someThread = new SuicidingThread(somethingRunnable, 5, TimeUnit.DAYS);

So this would be an usecase for extending thread.

like image 166
skiwi Avatar answered Oct 22 '22 19:10

skiwi


Specializing means, extend the functionality of existing Thread class. It could be anything depending on the application requirement. The one I've mentioned below may not be true logically.

public class MyThread extends Thread{
@Override
public void interrupt() {
    if(thread has started some operation on database){
        //roll back transaction
    }
    super.interrupt();
}
}

Here before interrupting the thread, we can check if any database operation is running currently and roll back it. Though it can be done from the interrupted catch block, handling it from extended class reduce the number of lines if you create lots of instances of this thread at different places in the application. It's just an example, nobody will use it this way. :)

like image 23
hanish.kh Avatar answered Oct 22 '22 21:10

hanish.kh