Thread Sleep




public class ThreadSleep extends Thread {
 
   
    public void run (){
       
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000) ;
                System.out.println("thread is about to sleep"+i); // repeated for 1 sec interval
            } catch (Exception e) {
                System.out.println(e);
            }
         
        }
}
    public static void main(String[] args) {
        ThreadSleep obj = new ThreadSleep();
       // obj.start();
     
   
        //obj.start();// this shows that we can start a thread twice but only by taking different references
       //obj.stop();
   
         ThreadSleep obj1 = new ThreadSleep();
        //when two run method are called simultaneously then they are treated as seperate object and are executed seperately
         obj.run();
        obj1.start();
        // calling run method directly will run the run method directly and if we call 2 run methods they will run one by one
// obj.run();
     //   obj1.run();
    }
 
}


OUTPUT

thread is about to sleep0
thread is about to sleep1
thread is about to sleep2
thread is about to sleep3
thread is about to sleep4
thread is about to sleep0
thread is about to sleep1
thread is about to sleep2
thread is about to sleep3
thread is about to sleep4
BUILD SUCCESSFUL (total time: 10 seconds)

No comments:

Post a Comment