/* * 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. THE COPYRIGHT HOLDER 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 - michael@michael-thomas.com * @version 1.0 07/04/08 */ package firststeps; public class ThreadsHelloWorldWaysThread extends Thread { /* * 2nd option to create a Thread. * Not as popular or flexible but very easy. * Not as flexible because your class must subclass "Threads". * Not as popular because it is not as flexible as implementing "Runnable". */ public ThreadsHelloWorldWaysThread(String strThreadName) { //Class constructor - We use this to give a name we specify to the Object. super(strThreadName); } public ThreadsHelloWorldWaysThread() { //Class constructor - We need this because we specified the constructor above! super(); } public void run() { String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Hello World from a thread! (subclasses Thread)"); } public static void main(String args[]) { //Creates a new thread. TheJVM gives the thread a name. ThreadsHelloWorldWaysThread objThreadHW1 = new ThreadsHelloWorldWaysThread(); objThreadHW1.start(); //Creates a new thread. The JVM gives the thread a name. (new ThreadsHelloWorldWaysThread()).start(); //One line example. //Creates a new thread named ThreadHW2. ThreadsHelloWorldWaysThread objThreadHW2 = new ThreadsHelloWorldWaysThread("ThreadHW2"); objThreadHW2.start(); //Creates a new thread named ThreadOneLine1 (new ThreadsHelloWorldWaysThread("ThreadOneLine1")).start(); //One line option //Anonymous class thread. new Thread(new Runnable() { public void run() { String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Hello World from a thread! (anonymous class) (subclasses Thread)"); } },"ThreadAnonymousClass").start(); } }