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.

http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread

Two ways for Threads

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

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

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

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:

WordPress.com Logo

You are commenting using your WordPress.com 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