What are the different ways of threads usage?

  • We can define and implement a thread in java using two ways:
    • Extending the Thread class

class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
InterviewBitThreadExample ib = new InterviewBitThreadExample();
ib.start();
}
}

implementing the Runnable interface

class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}

Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack

In modern Java, JDK ≥ 8, if you are explicitly using Java threads, then in all likelihood, you are doing it wrong.

Java still has shared memory multi-threading as per early version of Java, but over the years, it has become clear that application programmers should be using libraries and frameworks that manage all the issues of threads. JDK ≥ 11 has some very useful support libraries, not least of which is .parallel() which can be called on Steams for data parallel algorithms.

Application programmers should be working in abstractions of higher level than threads: concepts such as data parallelism, active objects, actors, stc. all based on message passing, are the tools of concurrency and parallelism for the applications programmer. Quasar and GPars are examples of frameworks supporting these ideas.

The only people who should be using threads explicitly are the people developing and maintaining the libraries and frameworks that support applications code.