Threads
Threads
CLASS-12
Threads
1. Define Threads
A multithreaded program consists of two or more parts called threads each of which can execute a
different task independently at the same time. In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
2. How threads can be created in Java? Explain with example
In Java, threads can be created in two ways
1. By extending the Thread class
public class ExtendThread extends Thread {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}
}
public static void main(String args[]) {
ExtendThread t1 =new ExtendThread();
t1.start();
}
}
public static void main(String args[]){
t1.start();
The run() method is the entry point for every new thread that is instantiated from the class.
4. Define start method of Thread class.
The start() method is invoked to start the execution of thread.
5. What is the difference between creating thread by extending the Thread class and by
implementing Runnable interface.
Classes that you create by extending the Thread class cannot be extended further. However,
Implementing the Runnable interface gives the flexibility to extend classes created by this method.