Thread.sleep to display 10 natural numbers

This is a simple java program to execute thread sleep. Sleep is one of the thread methods. Every process contains many threads. Using java, we can control those threads by codes. While calling thread.sleep, then that thread will sleep up to its sleep time. At the time of child thread sleep, program control will go to the main of that program.

This is a simple java program code to display natural numbers up to 20 using thread. So we can see printing of numbers one by one as slowly depending upon sleep time.
Giving more sleeping time in main than child function will help to complete and perfect execution of a program.
Here this class implementing ‘Runnable’ interface of default package java.lang.
At the time of starting a thread (here: t.start()), then abstract method of Runnable ‘run()’ will execute.
Here the name of class is ‘mythread’, so you should save your program with the name ‘mythread.java’.

Program code:

 class mythread implements Runnable
{
 Thread t;
 mythread()
 {
   t = new Thread(this, "hello");
   t.start();
 }
public void run()
{
 for(int i =1;i<=10;i++)
 {
 try
   {
  System.out.println(i);
  Thread.sleep(500);
   }
  catch(InterruptedException e)
    {

    }
 }
}

public static void main(String p[])
{
try
  {
   mythread ab = new mythread();
   Thread.sleep(1000);
  }
 catch(InterruptedException e)
    {

    }
}
}

Output:

Thread sleep implementation natural numbers




No comments:

Post a Comment