Java
  Home arrow Java arrow Page 8 - 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 / 322
    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 - Synchronizing Threads


    (Page 8 of 10 )

    A major concern when two or more threads share the same resource is that only one of them can access the resource at one time. Programmers address this concern by synchronizing threads, much the same way baseball players take turns being up to bat.

    Threads are synchronized in Java through the use of a monitor. Think of a monitor as an object that enables a thread to access a resource. Only one thread can use a monitor at any one time period. Programmers say that the thread owns the monitor for that period of time. The monitor is also called a semaphore.

    A thread can own a monitor only if no other thread owns the monitor. If the monitor is available, a thread can own the monitor and have exclusive access to the resource associated with the monitor. If the monitor is not available, the thread is suspended until the monitor becomes available. Programmers say that the thread is waiting for the monitor.

    Fortunately, the task of acquiring a monitor for a resource happens behind the scenes in Java. Java handles all the details for you. You do have to synchronize the threads you create in your program if more than one thread will use the same resource.

    You have two ways in which you can synchronize threads: You can use the synchronized method or the synchronized statement.

    The Synchronized Method

    All objects in Java have a monitor. A thread enters a monitor whenever a method modified by the keyword synchronized is called. The thread that is first to call the synchronized method is said to be inside the method and therefore owns the method and resources used by the method. Another thread that calls the synchronized method is suspended until the first thread relinquishes the synchronized method.

    If a synchronized method is an instance method, the synchronized method activates the lock associated with the instance that called the synchronized method, which is the object known as this during the execution of the body of the method. If the synchronized method is static, it activates the lock associated with the class object that defines the synchronized method.

    Before you learn how to define a synchronized method in your program, let’s see what might happen if synchronization is not used in a program. This is the objective of the following example. This program displays two names within parentheses using two threads. This is a three-step process, where the opening parenthesis, the name, and the closing parenthesis are displayed in separate steps.

    The example defines three classes: the Parentheses class, the MyThread class, and the Demo class, which is the program class. The Parentheses class defines one method called display(), which receives a string in its argument list and displays the string in parentheses on the screen. The MyThread class defines a thread. In doing so, the constructor of MyThread requires two arguments. The first argument is a reference to an instance of the Parentheses class. The second argument is a string containing the name that will be displayed on the screen. The run() method uses the instance of the Parentheses class to call its display() method, passing the display() method the name that is to appear on the screen.

    The rest of the action happens in the main() method of the Demo class. The first statement declares an instance of the Parentheses class. The next two classes create two threads. Notice that both threads use the same instance of the Parentheses class.

    Here’s what is displayed when you run this program. It’s probably not what you expected to see. Each name should be enclosed within its own parentheses. The problem is that the display() method isn’t synchronized.


    NOTE:   If a variable is assigned by one thread and is used or assigned by other threads, all access to the variable should be enclosed in a synchronized method or a synchronized statement.

      (Bob(Mary)
    )
    class Parentheses {
       void display(String s) {
       System.out.print ("(" + s);
       try {
         
    Thread.sleep (1000);
       } catch (InterruptedException e) {
           
    System.out.println ("Interrupted");
       }
       System.out.println(")");
     
    }
    }
    class MyThread implements Runnable {
      
    String s1;
       Parentheses p1;
       Thread t;
       public MyThread (Parentheses p2, String s2) {
         
    p1= p2;
          s1= s2;
          t = new Thread(this);
          t.start();
      
    }
       public void run() {
         p1.display(s1);
      
    }
    }
    class Demo{
      
    public static void main (String args[]) {
         Parentheses p3 = new Parentheses();
         MyThread name1 = new MyThread(p3, "Bob");
         MyThread name2 = new MyThread(p3, "Mary");
         try {
           
    name1.t.join();
            name2.t.join();
         } catch (InterruptedException e ) {
              System.out.println( "Interrupted");
         }
      }
    }

    The problem with the previous example is that two threads use the same resource concurrently. The resource is the display() method defined in the Parentheses class. In order to have one thread take control of the display() method, we must synchronize the display() method. This is done by using the keyword synchronized in the header of the display() method, which is illustrated in the next example.

    Here’s what is displayed when you run the next example. This is what you expected to see in the previous example.

    (Bob)
    (Mary)
    class Parentheses {
       synchronized void display(String s) {
       System.out.print ("(" + s);
       try {
         
    Thread.sleep (1000);
       } catch (InterruptedException e) {
           
    System.out.println ("Interrupted");
       }
       System.out.println(")");
     
    }
    }
    class MyThread implements Runnable {
      
    String s1;
       Parentheses p1;
       Thread t;
       public MyThread (Parentheses p2, String s2) {
         
    p1= p2;
          s1= s2;
          t = new Thread(this);
          t.start();
      
    }
       public void run() {
         p1.display(s1);
      
    }
    }
    class Demo{
      
    public static void main (String args[]) {
         Parentheses p3 = new Parentheses();
         MyThread name1 = new MyThread(p3, "Bob");
         MyThread name2 = new MyThread(p3, "Mary");
         try {
            
    name1.t.join();
            name2.t.join();
       } catch (InterruptedException e ) {
            System.out.println( "Interrupted");
       }
      }
    }

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