/**
    our first thread example

    @author Sharon Tuttle
    @version 2021-10-18
*/

public class ThreadPlay1
{
    // default constructor will do

    /**
        try to start up a thread that writes to the screen;
        I'll keep writing for about 20 seconds, and then I'll
        interrupt it

        @param args not used here 
    */

    public static void main(String[] args)
    {
        // create a Runnable object (the tasks in this lambda expression
	//    WILL be the run method's tasks!)

	Runnable myRunnable =
	    () ->
	    {
		// Thread class has a static method currentThread
		//    that returns a reference to the currently-executing
		//    thread

		Thread executingThread = Thread.currentThread();

		// loop until I am interrupted

		boolean finished = false;
		int counter = 0;

		while (!finished)
		{
		    try
		    {
			// Thread has a static method sleep that causes
			//    the current thread to pause/wait for
			//    approximately that many milliseconds
                        // (it MIGHT throw InterruptedException,
			//    and it is a *checked* exception that MUST
			//    be either caught, or thrown by this method)
			
			Thread.sleep(1000);

			System.out.println(counter + " - printed by thread: "
					   + executingThread.getName());
			counter++;
		    }
		    catch (InterruptedException exc)
		    {
			finished = true;
		    }
		}
	    };

	// use that Runnable object to create a named thread

	Thread myThread = new Thread(myRunnable, "Thread ONE!");

	// start up a new thread, and execute its run method actions
	//    in that new thread

	System.out.println("From main: about to set up Thread ONE!");
	myThread.start();

	// this main will now sleep for a bit...

	try
	{
	    System.out.println("From main: about to sleep");
	    Thread.sleep(10000);   // about 10 seconds/10,000 milliseconds
	}
	catch (InterruptedException exc)
	{
	    System.out.println("From main: got interrupted?!?");
	}

	// interrupt my thread, to politely request that it stop

	System.out.println("From main: about to interrupt Thread ONE!");
	myThread.interrupt();
    }
}