Threads can be created in two ways:
- Implementing java.lang.Runnable interface
- Extending java.lang.Thread class
-------------Program to create thread by implementing java.lang.Runnable----------------------
Create Runnable object, pass it in thread constructor. But our thread is not going to start until we call thread.start(), calling start() method internally calls run() method.
class MyRunnable implements Runnable{
public void run(){ //overrides Runnable's run() method
System.out.println("in run() method");
}
}
public class MyClass {
public static void main(String args[]){
MyRunnable runnable=new MyRunnable();
Thread thread=new Thread(runnable);
thread.start();
}
}
// in run() method
|
-------------Program to create thread by implementing java.lang.Thread----------------------
Thread creation by extending java.lang.Thread class.
We will create object of class which extends Thread class :
MyThread obj=new MyThread();
class MyThread extends Thread{
public void run(){ //overrides Thread's run() method
System.out.println("in run() method");
System.out.println("currentThreadName= "+Thread.currentThread().getName());
}
}
public class MyClass {
public static void main(String args[]){
System.out.println("currentThreadName=+Thread.currentThread().getName());
MyThread obj=new MyThread();
obj.start();
}
}
/*OUTPUT
currentThreadName= main
in run() method
currentThreadName= Thread-1
*/
|
No comments:
Post a Comment