//==============================================================================
// Terminating (interrupting) a thread   - Catching InterruptedException
// Main starts a thread
// Thread counts from 1 to 100 slowly (sleeps 2 sec in between counts)
// Everytime thread wakes up from sleep, it automatically checks interrupted flag
// Main interacts with user, and loops until the user enter 'stop'
// When 'stop' is entered, main will interrupt the thread, then terminate.
//==============================================================================
import java.util.Scanner;

public class TerminateThread1
{
    public static void main(String[] args)
    {
        TerminateThread1count o = new TerminateThread1count();	//create a program object

        Thread t1 = new Thread(o);          //create a thread, and give it pgm obj.
                
        t1.start();                         //make the thread eligible to run

        System.out.println("main - Enter 'stop' to terminate thread \n");

        Scanner sc = new Scanner(System.in);

        String s = "";
        while (! s.equals("stop"))
            s = sc.next();                  //get next token
        
        t1.interrupt();                     //signal to interrupt the thread                        

        System.out.println("main - nothing else to do - goodbye");
        System.out.println("main completed.");
    }
}

class TerminateThread1count  implements Runnable
{
    public void run( )                             //must override method
    {
        for (int i = 1; i <= 20; i += 1)
        {
            System.out.println("thread 1 - count: " +  i);

            try
            {
                Thread.sleep(1000);                 //delay by 2 seconds
            }
            catch(InterruptedException e)           //catch interruption
            {
                System.out.println("thread 1 interrupted. \n");
                System.exit(0);
            }
        }
        System.exit(0);
    }
}