0

My question is that is there any reason for Thread class to implement Runnable interface by itself. Are there any specific use cases where overriding Thread makes more sense than implementing Runnable by design

  • 1
    This exact question has been asked on Stack Exchange: stackoverflow.com/questions/541487/… – BobDalgleish Jan 3 at 17:19
  • @BobDalgleish Thanks. I have already referred to the question before asking, that question compares the both approaches, but my question is specifically about when extending Thread makes sense – Bharat Jan 3 at 17:28
0

One of the examples mentioned on Javadoc's Thread page is the following:

 class PrimeThread extends Thread {
     long minPrime;
     PrimeThread(long minPrime) {
         this.minPrime = minPrime;
     }

     public void run() {
         // compute primes larger than minPrime
          . . .
     }
 }

Usage:

 PrimeThread p = new PrimeThread(143);
 p.start();

The intention is to be able to simply override Thread class and provide your own logic for the run method. While you can also directly pass a Runnable instance to Thread, this provides another means to be able to perform an asynchronous action requiring parameters to be provided.

Though I should probably mention that using Thread class in this way is deprecated. There are plenty of improved ways of launching threads in Java 8 and beyond. This article provides good reasons why you should probably prefer ExecutorService instead.

More recent examples include the use of streams, which is described in detail in this article, which generally are preferable even moreso than the ExecutorService if you don't need the fine-grain control over the threading.

Good luck!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.