/** * our first thread example * * @author Sharon Tuttle * @version 2015-10-19 */ public class ThreadPlay1 { /** * try to start up a thread that writes to the screen -- * I'll keep writing for about 20 seconds, * then I'll interrupt it * * @param args not used here */ public static void main(String[] args) { // create a Runnable object Runnable myRunnable = new MyFirstRunnable(); // use the Runnable object to create a couple of threads Thread myThread = new Thread(myRunnable, "Thread ONE!"); Thread mySecond = new Thread(myRunnable, "TWOOOOOOOO"); // and now start those threads going! System.out.println("From main: about to start up " + "my Thread ONE!"); myThread.start(); System.out.println("from main - howdy!"); try { Thread.sleep(3000); } catch (InterruptedException exc) { System.out.println("Huh? main got interrupted?"); } System.out.println("From main: about to start up " + "second thread"); mySecond.start(); System.out.println("from main - moo!"); try { System.out.println("from main - about to sleep for 17 " + "seconds"); Thread.sleep(17000); } catch (InterruptedException exc) { System.out.println("Huh? main 17-part got interrupted?"); } System.out.println("from main - about to interrupt" + "Thread ONE!"); // the PREFERRED way to "stop" a thread: // call its interrupt() method, and it is // expected to stop itself politely when that // happens myThread.interrupt(); System.out.println("from main - about to interrupt" + "second thread"); mySecond.interrupt(); System.out.println("ending main method"); } } /** * a first example of a class implementing the * Runnable interface */ class MyFirstRunnable implements Runnable { // what would happen if I had a static data field here? // (one copy, no matter how many instances) private static int racerVal = 13; /** * this thread just wants to write to * the screen about once every second */ public void run() { // you can get a reference to the current // running thread... Thread executingThread = Thread.currentThread(); boolean finished = false; int counter = 0; // loop until interrupted while (!finished) { try { // sleep for about 1 second Thread.sleep(1000); System.out.println(counter + " - printed by thread: " + executingThread.getName() + " and racerVal is: " + racerVal); counter++; racerVal++; } catch (InterruptedException exc) { finished = true; } } System.out.println("ENDING thread " + executingThread.getName()); } }