Multithread


In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.

Runnable interface

public class DemoRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//start new thread with a "new Thread(new demoRunnable()).start()" call

Thread class

public class DemoThread extends Thread {
    public DemoThread() {
        super("DemoThread");
    }
    public void run() {
        //Code
    }
}
//start new thread with a "new demoThread().start()" call

Difference between the two:

  • Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go.
  • Java only supports single inheritance, so you can only extend one class.
  • Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
  • Implementing Runnable makes your class more flexible.

results matching ""

    No results matching ""