In this program, two threads are created along with the "main" thread. The currentThread() method of the Thread class returns a reference to the  currently executing thread and the getName( ) method returns the name of the thread. The sleep( ) method pauses execution of the current thread for 1000 milliseconds(1 second) and switches to the another threads to execute it. At the time of execution of the program, both threads are registered with the thread scheduler and the CPU scheduler executes them one by one.

 

class SampleThread extends Thread{
SampleThread(String s){
 
super(s);
 start();
 }
 public void run(){
 for(int i=0;i<5;i++){
System.out.println("Thread Name :"
 +Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
 public class MultiThread1{
public static void main(String args[]){
System.out.println("Thread Name:"
 +Thread.currentThread().getName());
SampleThread m1=new SampleThread("My Thread 1");
SampleThread m2=new SampleThread("My Thread 2");
}
}

 

output of the program is

Thread Name:main

Thread Name :My Thread 1

Thread Name :My Thread 2

Thread Name :My Thread 1

Thread Name :My Thread 2

Thread Name :My Thread 1

Thread Name :My Thread 2

Thread Name :My Thread 1

Thread Name :My Thread 2

Thread Name :My Thread 1

Thread Name :My Thread 2

 

Related Reading:

 

Program to create multiple threads using Runnable interface.




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)