/* * 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; import java.util.Date; public class ThreadsHelloWorldJoinSimple implements Runnable { public void run() { //The Thread's run() method. int intLoopCount = 5; String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Start Time - " + (new Date()).toString()); for (int i = 1; i <= intLoopCount; i++) { //Pause for 2 seconds try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { System.out.println(strThreadName + " - Interrupted Time - " + (new Date()).toString()); return; } System.out.println( strThreadName + " - Hello World #" + i + " - " + (new Date()).toString()); } System.out.println(strThreadName + " - Stop Time - " + (new Date()).toString()); } public static void main(String args[]) throws InterruptedException { String strThreadName = Thread.currentThread().getName(); System.out.println(strThreadName + " - Begin - " + (new Date()).toString()); //First Thread ThreadsHelloWorldJoinSimple objRunnable1 = new ThreadsHelloWorldJoinSimple(); Thread objThreadHW1 = new Thread(objRunnable1, "ThreadHW1"); //Second Thread ThreadsHelloWorldJoinSimple objRunnable2 = new ThreadsHelloWorldJoinSimple(); Thread objThreadHW2 = new Thread(objRunnable2, "ThreadHW2"); objThreadHW1.start(); //Start this thread, then continue on. objThreadHW1.join(); //Pauses the main()'s thread until objThreadHW1 completes. System.out.println(strThreadName + " - before objThreadHW2.start() " + (new Date()).toString()); objThreadHW2.start(); //Start this thread, then continue on. System.out.println("From main(), Finished - " + (new Date()).toString()); //Notice that the main tread will finish before the ThreadHW2 complete. } }