/* * Copyright (c) Michael Thomas, All Rights Reserved. (michael@michael-thomas.com) * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Exceptions must be in writing between the * copyright holder and entity using the content. * * THE COPYRIGHT HOLDER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * @author Michael Thomas * @version 1.0 07/04/08 */ package firststeps; public class ThreadsHelloWorldWaysRunnable implements Runnable { /* * 1st option to create a Thread. * Most popular because it is flexible. * It's flexible because you can subclass any desired class. */ public ThreadsHelloWorldWaysRunnable() { //Class constructor - We didn't really need this for this example!!! super(); } public void run() { //Note: the .start() method makes the thread active and then calls this method. String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Hello World from a thread! (implement Runnable)"); } public static void main(String args[]) { //Create a new thread named: ThreadHW1 ThreadsHelloWorldWaysRunnable objRunnable = new ThreadsHelloWorldWaysRunnable(); Thread objThreadHW1 = new Thread(objRunnable,"ThreadHW1"); objThreadHW1.start(); //Create a new thread named: ThreadHW2 (new Thread(new ThreadsHelloWorldWaysRunnable(),"ThreadHW2")).start(); //One line example. //Create a new thread and let the JVM give it a name. (new Thread(new ThreadsHelloWorldWaysRunnable())).start(); //One line Example. //Create a new thread from an Anonymous Class and then starts the class. new Thread(new Runnable() { public void run() { String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Hello World from a thread! (anonymous class) (implement Runnable)"); } },"ThreadAnonymousClass").start(); } }