Create three threads (by using Thread class and Runnable interface) where the first thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds.

 class NewThread implements Runnable

{
    String name,m; // name of thread
   

    int st;
    NewThread(String threadname,String msg,int time)
    {  
        name = threadname;
        m=msg;
        st=time;
        Thread t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start();          // Start the thread
    }
    // This is the entry point for thread.
    public void run()
    {
        try
        {
            for(i=0;i<10;i++)
            {
                System.out.println(m);
                Thread.sleep(st);
            }
        }
        catch (InterruptedException e)
        {
            System.out.println(name + "Interrupted");
        }
        System.out.println(name + " exiting.");
    }
}

public class THREAD{
    public static void main(String args[])
    {
        new NewThread("One","Good Morning",1000); // start threads
        new NewThread("Two","Hello",2000);
        new NewThread("Three","Welcome",3000);
       
        try
        {
            // wait for other threads to end
            //System.out.println("123");
            Thread.sleep(10000);
        }
        catch (InterruptedException e)
        {
            System.out.println("Main thread Interrupted");
        }
        System.out.println("Main thread exiting.");
    }
}


Comments

Popular posts from this blog

Design GUI to handle Choice Control event.

Write a Java program that reads an integer number (between 1 and 255) from the user and prints the binary representation of the number. The answer should be printed as a String. Note: The output displayed should contain 8 digits and should be padded with leading 0s(zeros), in case the returned String contains less than 8 characters. For example, if the user enters the value 16, then the output should be 00010000 and if the user enters the value 100, the output should be 01100100 (Hint : You may use String.format() method for the expected output)