Thread:
A thread is a light-weight process which can run independently. A java program can contain multiple threads. Every thread is created and controlled by the java.lang.Thread class. We can create threads in two ways:
- By extending Thread class
- By implementing Runnable interface.
Creating Thread by extending Thread class:
class ThreadDemo extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
ThreadDemo tr=new ThreadDemo();
tr.start();
}
}
Here we are extending Thread class to Create a thread.
Creating Thread by implementing Runnable interface:
class ThreadDemo implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
ThreadDemo m1=new ThreadDemo();
Thread t1 =new Thread(m1); //passing the object of ThreadDemo class that implements Runnable
t1.start();
}
}
If we implement runnable interface then we have to explicitly create Thread class object
0 Comment(s)