Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simple program of "Thread" !!!!!

Tags: thread
In this program, we are creating two thread and give them different sleep time. With the help of "Thread.sleep()" you can write down the milliseconds so that thread can start run after defined seconds. And to start the thread, we simple write "t1.start()" in this program, to start the particular thread. And in the last, "t1.isAlive()" is the boolean method to check the thread, whether it is alive or not !

In below program, we give 5 to 1 to first Thread and 6 to 1 to second. When both threads are start than it stops for the milliseconds that we wrote different for both of them so that you can identify that which thread is complete running and complete first. And for that, we also wrote the message that "Exit from xyz thread now........." for confirmation from thread ! 




class createThread extends Thread{

public void run(){
try{
for(int i=5;i>0;i--){
System.out.println(i);
Thread.sleep(500);
}
}catch(InterruptedException e){}
System.out.println("Exit from first thread now.....");
}
}

class createThread2 extends Thread{

public void run(){
try{
for(int j=6;j>0;j--){
System.out.println(j);
Thread.sleep(1000);
} }
catch(InterruptedException e){}
System.out.println("Exit from second thread............");
}

}


public class trythread {


public static void main(String[] args) {


createThread t1= new createThread();
createThread2 t2=new createThread2();
t1.start();
t2.start();
System.out.println("First thread is alive: "+t1.isAlive());
System.out.println("Second thread is alive: "+t2.isAlive());
}

}
____________________________________________________
Output:

Second thread is alive: true
6
5
4
3
5
2
1
4
Exit from first thread now.....
3
2
1
Exit from second thread............





This post first appeared on LET's START CORE JAVA !, please read the originial post: here

Share the post

Simple program of "Thread" !!!!!

×

Subscribe to Let's Start Core Java !

Get updates delivered right to your inbox!

Thank you for your subscription

×