Implementing the sleep ()

Example program:

Class Sdemo1 extends Thread

{

Public void run ()

{

Try

{

Thread .sleep (837);

}

Catch (Exception e)

{

System. Out. Prinln(e);

}

For (int i=0; i<37; i++)

System. Out. Prinln(“ run of Sdemo1: “+i);

System. Out. Prinln(“end of run()”);

}

Public static void main (string args [ ])

{

Sdemo1 s1 = new sdemo1 ();

S1. Start ();

For (int i= 400; i< 440; i++)

System. Out. Prinln(“inside main : +i”);

System. Out. Prinln(“end of main ()”);

}

}

  • We know that, sleep () method is proven to generate checked exceptions. Therefore the function call should be made inside the try block.
  • Suppose, if we want to skip the try block, then we should use Throws Exception in the function signature in which sleep () method is called.
  • But, this leads to a problem, because, if we use throws Exception in the definition of run () method, then, we directly violate the concept of overriding.
  • The signature of run () method defined in Thread class is just public void run (). It does not have any Throws Exception. Now, if we add this to our run method, then we are not overriding run () of thread class.
  • When we call start () method, it searches for the overridden run () method and when it does not find any, it gives a complication error.
  • Thus, Throws Exception cannot be used with run () method and compulsory we have to use try-catch inside run () in order to call the sleep () method.
  • We know that main () is also thread and other threads getting executed simultaneously with main (). Suppose, if we use thread. Sleep () in main, then what happens?

Implementing the Sleep Homework Help

Tutorspoint.com provides Professional Java Assignment Help, help with java programming assignment, live java programming homework help, Matlab programming assignment help to college students & final year university students in their java project help, semester & paper writing help