Java
  Home arrow Java arrow Page 6 - Multithreading in Java
IBM Rational Software Development Conference
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Download TestComplete 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
eWeek
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Multithreading in Java
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 191
    2005-08-04

    Table of Contents:
  • Multithreading in Java
  • Overhead
  • The Thread Classes and the Runnable Interface
  • Creating Your Own Thread
  • Creating a Thread by Using extends
  • Using isAlive() and join()
  • Setting Thread Priorities
  • Synchronizing Threads
  • Using the Synchronized Statement
  • Suspending and Resuming Threads

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Multithreading in Java - Using isAlive() and join()
    (Page 6 of 10 )

    Typically, the main thread is the last thread to finish in a program. However, there isn’t any guarantee that the main thread won’t finish before a child thread finishes. In the previous example, we told the main method to sleep until the child threads terminate. However, we estimated the time it takes for the child threads to complete processing. If our estimate was too short, a child thread could terminate after the main thread terminates. Therefore, the sleep technique isn’t the best one to use to guarantee that the main thread terminates last.

    Programmers use two other techniques to ensure that the main thread is the last thread to terminate. These techniques involve calling the isAlive() method and the join() method. Both of these methods are defined in the Thread class.

    The isAlive() method determines whether a thread is still running. If it is, the isAlive() method returns a Boolean true value; otherwise, a Boolean false is returned. You can use the isAlive() method to examine whether a child thread continues to run. The join() method works differently than the isAlive() method. The join() method waits until the child thread terminates and “joins” the main thread. In addition, you can use the join() method to specify the amount of time you want to wait for a child thread to terminate.

    The following example illustrates how to use the isAlive() method and the join() method in your program. This example is nearly the same as the previous example. The difference lies in the main() method of the Demo class definition.

    After the threads are declared using the constructor of the MyThread class, the isAlive() method is called for each thread. The value returned by the isAlive() method is then displayed on the screen. Next, the join() method is called for each thread. The join() method causes the main thread to wait for all child threads to complete processing before the main thread terminates.

    Here is what is displayed on the screen when this program runs:

    Thread Status: Alive
    Thread 1: true
    Thread 2: true
    Thread 3: true
    Thread 4: true
    Threads Joining.
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 1
    Terminating thread: 2
    Terminating thread: 3
    Terminating thread: 4
    Thread Status: Alive
    Thread 1: false
    Thread 2: false
    Thread 3: false
    Thread 4: false
    Terminating thread: main thread.
    class MyThread implements Runnable {
      String tName;
      Thread t;
      MyThread (String threadName) {
        
    tName = threadName;
         t = new Thread (this, tName);
         t.start();
      }
      public void run() {
        
    try {
             System.out.println("Thread: " + tName );
             Thread.sleep(2000);
        
    } catch (InterruptedException e ) {
           System.out.println("Exception: Thread "
                   
    + tName + " interrupted");
         }
         System.out.println("Terminating thread: " + tName );
     
    }
    }
    class Demo {
       public static void main (String args []) {
          MyThread thread1 = new MyThread ("1");
          MyThread thread2 = new MyThread ("2");
          MyThread thread3 = new MyThread ("3");
          MyThread thread4 = new MyThread ("4");
          System.out.println("Thread Status: Alive");
          System.out.println("Thread 1: "
                   
    + thread1.t.isAlive());
          System.out.println("Thread 2: "
                   
    + thread2.t.isAlive());
          System.out.println("Thread 3: "
                   
    + thread3.t.isAlive());
          System.out.println("Thread 4: "
                   
    + thread4.t.isAlive());
         
    try {
             System.out.println("Threads Joining.");
             thread1.t.join();
             thread2.t.join();
             thread3.t.join();
             thread4.t.join();
         
    } catch (InterruptedException e) {
            System.out.println(
                     
    "Exception: Thread main interrupted.");
          }
          System.out.println("Thread Status: Alive");
          System.out.println("Thread 1: "
                   
    + thread1.t.isAlive());
          System.out.println("Thread 2: "
                   
    + thread2.t.isAlive());
          System.out.println("Thread 3: "
                   
    + thread3.t.isAlive());
          System.out.println("Thread 4: "
                   
    + thread4.t.isAlive());
          System.out.println(
                    "Terminating thread: main thread."); 
     
    }
    }

    More Java Articles
    More By McGraw-Hill/Osborne


       · Keep up the Good work sir.Thanks Kiran
       · This is the best introduction to multithreading i ever had......Thanks a...
       · Hello sir, this is the best online tutorial on multithreading, I have seen many but...
       · Hi,This is really a good tutorial on multithreading concept for begineers. It...
       · It is very easy to understand,with simple language.I.V.N.Venu
       · Example in chapter Five is not so Elucidate.I.V.N.Venu
       · Great job....Thanks alot ...Sanesh
       · sir i have read u r notes it's very easy to understand,very good sir
       · This is trully a very good article as it covers in one piece all the important...
       · Why does all the indian programmers say "sir"? Guys you r not in a school and the...
       · Good Job.It helps me a lot...Keep Going
       · The Hindi Language has an equivalent of "sir" that's used to address any stranger as...
       · This is the best platform from where I can learnmultithreading,thanks..Paresh
       · It is very easy to learn
       · it is very useful n connecting the sources indeed
       · Nice job..Good Article...Very nice..Rakesh..
       · The tutorial is nice, but in chapter 9, when I tried to run the program with wait()...
       · this is very good and easy to read and understand,but the whole data of threads...
       · I found good matter on multithreadig which help me a lot to understand...
       · Please check the sample example.After some analysis, I found the busy flag is...
       · Hi ,It is not much because of the language, its got more to do the with the...
     

    Buy this book now. This article is excerpted from chapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548). Check it out at your favorite bookstore today. Buy this book now.

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...

    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway