/** our second thread example - now with several more threads! @author Sharon Tuttle @version 2021-10-10 */ public class ThreadPlay2 { /** try to set up 3 threads, interrupt them after about 30 seconds @param args not used here */ public static void main(String[] args) { Runnable[] myRunnables = new Runnable[3]; Thread[] myThreads = new Thread[3]; String[] threadNames = {"Thread #1", "thread TWO", "t-number 3!"}; // create Runnable objects Runnable mySecondRunnable = () -> { // get a reference to the running thread Thread executingThread = Thread.currentThread(); // work in a slight time-stagger int sleepAmt = getStaggeredSleepAmt(executingThread); // loop until interrupted boolean finished = false; int counter = 0; while (!finished) { try { Thread.sleep(sleepAmt); System.out.println(counter + " - printed by thread: " + executingThread.getName()); counter++; } catch(InterruptedException exc) { finished = true; } } }; // add these to my array and set up and start these threads for (int i=0; i<3; i++) { myRunnables[i] = mySecondRunnable; myThreads[i] = new Thread(myRunnables[i], threadNames[i]); myThreads[i].start(); } // main will now sleep for a while try { System.out.println("From main: about to sleep"); Thread.sleep(30000); } catch(InterruptedException exc) { System.out.println("From main: got interrupted?!"); } // interrupt my threads to politely request they end for (int i=0; i<3; i++) { myThreads[i].interrupt(); } } /** returns a staggered sleep amount based on the thread */ private static int getStaggeredSleepAmt(Thread chosenThread) { if (chosenThread.getName().equals("Thread #1")) { return 1000; } else if (chosenThread.getName().equals("thread TWO")) { return 2000; } else if (chosenThread.getName().equals("t-number 3!")) { return 3000; } else // should NOT reach here! { System.err.println("getStaggeredSleepAmt: " + "called with BAD thread named: " + chosenThread.getName()); return 0; } } }