Aryan PrajapatKnowledge Contributor
What are the different ways of thread usage?
What are the different ways of thread usage?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
There are two ways to define and implement a thread in Java. They are by implementing the runnable interface and extending the thread class.
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.