Java
  Home arrow Java arrow Page 4 - 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 / 321
    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 Your Own Thread


    (Page 4 of 10 )

    Remember, your program is the main thread, and other portions of your program can also be a thread. You can designate a portion of your program as a thread by creating your own thread. The easiest way to do this is to implement the Runnable interface. Implementing the Runnable interface is an alternative to your class inheriting the Thread class.

    An interface describes one or more method members that you must define in your own class in order to be compliant with the interface. These methods are described by their method name, argument list, and return value.

    The Runnable interface describes the method classes needed to create and interact with a thread. In order to use the Runnable interface in your class, you must define the methods described by the Runnable interface.

    Fortunately, only you need to define one method described by the Runnable interface—the run() method. The run() method must be a public method, and it doesn’t require an argument list or have a return value.

    The content of the run() method is the portion of your program that will become the new thread. Statements outside the run() method are part of the main thread. Statements inside the run() method are part of the new thread. Both the main thread and the new thread run concurrently when you start the new thread, which you’ll learn how to do in the next example. The new thread terminates when the run() method terminates. Control then returns to the statement that called the run() method.

    When you implement the Runnable interface, you’ll need to call the following constructor of the Thread class. This constructor requires two arguments. The first argument is the instance of the class that implements the Runnable interface and tells the constructor where the new thread will be executed. The second argument is the name of the new thread. Here’s the format of the constructor:

    Thread (Runnable class, String name)

    The constructor creates the new thread, but it does not start the thread. You explicitly start the new thread by calling the start()method. The start() method calls the run() method you defined in your program. The start() method has no argument list and does not return any values.

    The following example illustrates how to create and start a new thread. Here’s what is displayed when this program runs:

    Main thread started
    Child thread started
    Child thread terminated
    Main thread terminated


    NOTE:   The output of this program may be different when you run this program. Some Java run-time environments terminate the main thread before the child thread, whereas others terminate the child thread before the main thread. Therefore, the text shown here might appear in a different order when you run this program.

    class MyThread implements Runnable{
       Thread t;
       MyThread () {
         
    t = new Thread(this,"My thread");
         
    t.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");
       }
    }

    This example begins by defining a class called MyThread, which implements the Runnable interface. Therefore, we use the keyword implements to implement the Runnable interface. Next, a reference to a thread is declared. Defining the constructor for the class follows this. The constructor calls the constructor of the Thread class. Because we are implementing the Runnable interface, we need to pass the constructor reference to the instance of the class that will execute the new thread and the name of the new thread. Notice that we use the keyword this as reference to the instance of the class. The keyword this is a reference to the current instance of the class.

    The constructor returns a reference to the new thread, which is assigned to the reference declared in the first statement in the MyThread class definition. We use this reference to call the start() method. Remember that the start() method calls the run() method.

    Next,we define the run() method. Statements within the run() method become the portion of the program that executes when the thread executes. There are only two displayed statements in the run() method. Later in this chapter, we’ll expand the run() method to include more interesting statements.

    Next, we define the program class. The program class explicitly executes the new thread by creating an instance of the MyThread class. This is done by using the new operator and calling the constructor of MyThread.

    Finally, the program finishes by displaying two lines on the screen.

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

    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 1 Hosted by Hostway
    Stay green...Green IT