//==============================================================================
// Terminating (interrupting) a thread   - Frequently checking isInterrupted()
// Main starts a thread
// Thread counts from 1 to 50000
// Every 1000 iteration, thread checks isInterrupted() 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 TerminateThread2
{
    public static void main(String[] args)
    {
        Thread t1 = new TerminateThread2count();  //create a thread from this program object

        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 TerminateThread2count  extends Thread
{
    public void run( )                              //must override method
    {
        for (int i = 1; i <= 50000; i++)
        {
            System.out.println("thread 1 - count: " +  i);

            if (i % 1000 == 0)                      //for every 1000 iterations
                if (isInterrupted() )               //check if it has been interrupted
                {
                    System.out.println("thread 1 interrupted. \n");
                    System.exit(0);
                }    
        }
        System.exit(0);
    }
}