Java
  Home arrow Java arrow Page 5 - Multithreading in Java
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 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 / 324
    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
     
     
    ADVERTISEMENT


    Multithreading in Java - Creating a Thread by Using extends


    (Page 5 of 10 )

    You can inherit the Thread class as another way to create a thread in your program. As you’ll recall from Chapter 8, you can cause your class to inherit another class by using the keyword extends when defining your class. When you declare an instance of your class, you’ll also have access to members of the Thread class.

    Whenever your class inherits the Thread class, you must override the run() method, which is an entry into the new thread. The following example shows how to inherit the Thread class and how to override the run() method.

    This example defines the MyThread class, which inherits the Thread class. The constructor of the MyThread class calls the constructor of the Thread class by using the super keyword and passes it the name of the new thread, which is My thread. It then calls the start() method to activate the new thread.

    The start() method calls the run() method of the MyThread class. As you’ll notice in this example, the run() method is overridden by displaying two lines on the screen that indicate that the child thread started and terminated. Remember that statements within the run()method constitute the portion of the program that runs as the thread. Therefore, your program will likely have more meaningful statements within the definition of the run() method than those used in this example.

    The new thread is declared within the main() method of the Demo class, which is the program class of the application. After the thread starts, two messages are displayed, indicating the status of the main thread.

    class MyThread extends Thread {
      
    MyThread(){
        
    super("My thread");
        
    start();
      
    }
      
    public void run() {
          System.out.println("Child thread started");
          System.out.println("Child thread terminated");
      
    }
    }
    class Demo {
      
    public static void main (String args[]){
          new MyThread();
          System.out.println("Main thread started");
          System.out.println("Main thread terminated");
      
    }
    }


    NOTE:   As a rule of thumb, you should implement the Runnable interface if the run() method is the only method of the Thread class that you need to override. You should inherit the Thread class if you need to override other methods defined in the Thread class.

    Using Multiple Threads in a Program

    It is not unusual to need to run multiple instances of a thread, such as when your program prints multiple documents concurrently. Programmers call this spawning a thread. You can spawn any number of threads you need by first defining your own class that either implements the Runnable interface or inherits the Thread class and then declaring instances of the class. Each instance is a new thread.

    Let’s see how this is done. The next example defines a class called MyThread that implements the Runnableinterface. The constructor of the MyThreadclass accepts one parameter, which is a string that is used as the name of the new thread. We create the new thread within the constructor by calling the constructor of the Thread class and passing it a reference to the object that is defining the thread and the name of the thread. Remember that the this keyword is a reference to the current object. The start() method is then called, which calls the run() method.

    The run() method is overridden in the MyThread class. Two things happen when the run() method executes. First, the name of the thread is displayed on the screen. Second, the thread pauses for 2 seconds when the sleep() method is called. The sleep() method is defined in the Thread class can accept one or two parameters. The first parameter is the number of milliseconds the thread is to pause. The second parameter is the number of microseconds the thread pauses. In this example, we’re only interested in milliseconds, so we don’t need to include the second parameter (2,000 nanoseconds is 2 seconds). After the thread pauses, another statement is displayed on the screen stating that the thread is terminating.

    The main() method of the Demo class declares four instances of the same thread by calling the constructor of the MyThread class and passing it the name of the thread. Each of these is treated as a separate thread. The main thread is then paused 10 seconds by a call to the sleep() method. During this time, the threads continue to execute. When the main thread awakens, it displays the message that the main thread is terminating.

    Here’s what is displayed on the screen when this example runs:

    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 1
    Terminating thread: 2
    Terminating thread: 3
    Terminating thread: 4
    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 []) {
          new MyThread ("1");
          new MyThread ("2");
          new MyThread ("3");
          new MyThread ("4");
          try {
            
    Thread.sleep (10000);
          } catch (InterruptedException e) {
            System.out.println(
                    
    "Exception: Thread main interrupted.");
          }
          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...
       · I also found out the same thing. There should be a "busy=false" before notify in the...
       · it is the best way to express a multithreading,it is totally understandble ...
       · this was a great tutorial sir, I am a first timer and even I got to understand a lot...
       · This is the best tutorial on m-threading I've found ever! I love the language...
       · this book is very good:kishan
       · I got much information from this site about threading thank u verymuch
       · Very good article, thanks.I spotted one minor error: On page 5 it is...
       · thanks sir to describe multithreading so deeply....-ashutosh
       · I found this article is very useful. Keeg good work doing.Thanx
       · This write up us very simple to understand..I would like to thank author for...
       · Excellent work !! Here is the one among the very few who can explain things the...
       · I have never gone through such a brilliant concept on Multithreadind.I would like to...
       · Wonderful explanation of Multithreading.I impressed so much.Thanks a lot, keep...
       · this article is directly taken from "Java 2: Complete Reference" by herbert...
       · Sir, the article presented regarding MULTITHREADING concept was excellent. I could...
       · It is excellent explanation
       · this is really very good
       · its very nice information about multi threading -Ravinder Bisht
       · Example on page 9 would be better understood if "busy" had been called "full"...
       · It simply enables reders to fall in love with java-Tanmay
       · this is the best description of multithreading i'v ever read! gr8 work
       · sir this is xtremely superb.thanx for the notes dat u've put on.. now i understood...
       · sir this is xtremely superb.thanx for the notes dat u've put on.. now i understood...
       · I do believe it is a great tutorial. This really helped. It's much better than...
       · This article is very helpful to get understand about the multi-threading aspects in...
       · Such a nice tutorial i've ever read. i'd really thankful to the author of this...
       · Keep your tradition and slang language to yourself. This is computer language way...
       · Nice explanation sir...really appreciative
       · In your Publisher, Consumer example in get method of Queue class, boolean busy is...
     

    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...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek