thread in java

why “implements runnable” is preferred than “extends thread”

implements Runnable is the preferred way to do it, IMO. You’re not really specialising the thread’s behaviour. You’re just giving it something to run. That means composition is the philosophically “purer” way to go.

In practical terms, it means you can implement Runnable and extend from another class as well.

Two ways for Threads

class PrimeThread extends Thread {
   public void run() {
new PrimeThread().start();

 class PrimeRun implements Runnable {
    public void run() {
new Thread(new PrimeRun()).start()

2 thoughts on “thread in java

  1. Only use the second pattern, Runnable. It becomes even better in Java 8:

    class Prime {
    public void doSomething() { … }
    public void doSomethingElse() { … }

    Prime p = new Prime();
    new Thread( () -> { p.doSomething(); } );
    new Thread( () -> { p.doSomethingElse(); } );

    Logic exercise: Do we need to keep a reference to the Thread instance? Why or why not?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s