Stop thread execution with ctrl+c

Q. Write a program that creates 2 threads - each displaying a message (Pass the message as a parameter to the constructor). The threads should display the messages continuously till the user presses ctrl+c.

Answer:

If any application threads (daemon or nondaemon) are still running at shutdown time, then the user just presses the ctrl+c to stop thread execution.

Thread1.java

class Thread1 extends Thread
{
     String msg = "";
     Thread1(String msg)
     {
          this.msg = msg;
     }
     public void run()
     {
          try
          {
               while (true)
               {
                    System.out.println(msg);
                    Thread.sleep(300);
               }
          }
          catch (Exception ex)
          {
               ex.printStackTrace();
          }
     }
}


Thread2.java

class Thread2 extends Thread
{
     String msg = "";
     Thread2(String msg)
     {
          this.msg = msg;
     }
     public void run()
     {
          try
          {
               while (true)
               {
                    System.out.println(msg);
                    Thread.sleep(400);
               }
          }
          catch (Exception ex)
          {
               ex.printStackTrace();
          }
     }
}


ThreadDemo.java

class ThreadDemo
{
     public static void main(String[] args)
     {
          Thread1 t1 = new Thread1("Running Thread1....");
          Thread1 t2 = new Thread1("Running Thread2....");
          t1.start();
          t2.start();
     }
}


Output:

Run the ThreadDemo.java. Press ctrl+c to stop the execution of the running thread.

multiple thread