Java
  Home arrow Java arrow Page 9 - Multithreading in Java
IBM Rational Software Development Conference
The Best Selling PC Migration Utility.
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 
 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 / 193
    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 the Synchronized Statement
    (Page 9 of 10 )

    Synchronizing a method is the best way to restrict the use of a method one thread at a time. However, there will be occasions when you won’t be able to synchronize a method, such as when you use a class that is provided to you by a third party. In such cases, you don’t have access to the definition of the class, which prevents you from using the synchronized keyword.

    An alternative to using the synchronized keyword is to use the synchronized statement. A synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized. Calls to the methods contained in the synchronized block happen only after the thread enters the monitor of the object.

    Although you can call methods within a synchronized block, the method declaration must be made outside a synchronized block.

    The following example shows how to use a synchronized statement. This is basically the same as the previous example; however, the synchronized statement is used instead of the synchronized keyword. The synchronized statement is placed in the run() method within the MyThread class. The synchronized statement synchronizes the instance of the Parentheses class and thus prevents two threads from calling the display() method concurrently.

    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() {
           synchronized(p1){
              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");
         }
      }
    }

    Here, the display() method is not modified by synchronized. Instead, the synchronized statement is used inside the caller’s run()method. This causes the same correct output as before, because each thread waits for the prior one to finish before proceeding.

    Communicating Between Threads

    Threads have opened programmers to a new dimension in programming, where parts of a program can execute asynchronously, each processing independently of the other. However, sometimes threads have to coordinate their processing and therefore need to be able to communicate with each other during processing. Programmers call this interprocess communication.

    You can have threads communicate with each other in your program by using the wait(), notify(), and notifyAll() methods. These methods are called from within a synchronized method. The wait() method tells a thread to relinquish a monitor and go into suspension. There are two forms of the wait() method. One form doesn’t require an argument and causes a thread to wait until it is notified. The other form of the wait() method let’s you specify the amount of time to wait. You specify the length of time in milliseconds, which is passed to the wait() method.

    The notify() method tells a thread that is suspended by the wait()method to wake up again and regain control of the monitor. The notifyAll() method wakes up all threads that are waiting for control of the monitor. Only the thread with the highest priority is given control over the monitor. The other threads wait in suspension until the monitor becomes available again.

    The following example shows you how to use these methods in an application. The objective of the program is to have the Publisher class give a value to the Consumer class through the use of a Queue class. The Publisher class places a value on the queues and then waits until the Consumer class retrieves the value before the Publisher class places another value on the queue.

    This example defines four classes: the Queue class, the Publisher class, the Consumer class, and the Demo class. The Queue class defines two instance values: exchangeValue and a flag. The exchangeValue is used to store the value placed on the queue by the publisher. The flag variable is used as a sign indicating whether a value has been placed on the queue. This is set to false by default, which enables the producer to place a value on to the queue. The Queue class also defines a get() method and a put() method. The put() method is used to place a value on to the queue (that is, to assign a value to the exchangeValue variables). The get() method is used to retrieve the value contained on the queue (that is, to return the value of exchangeValue). Once the value is assigned, the put() method changes the value of the flag from false to true, indicating there is a value on the queue. Notice how the value of the flag is used within the get() method and the put() method to have the thread that calls the method wait until either there is a value on the queue or there isn’t a value on the queue, depending on which method is being called.

    The Publisher class declares an instance of the Queue class and then calls the put() method to place five integers on the queue. Although the put() method is called within a for loop, each integer is placed on the queue and then there is a pause until the integer is retrieved by the Consumer class.

    The Consumer class is very similar in design to the Publisher class, except the Consumer class calls the get() method five times from within a for loop. Each call to the get() method is paused until the Publisher class places an integer in the queue.

    The main() method of the Demo class creates instances of the Queue class, the Publisher class, and the Consumer class. Notice that both constructors of the Publisher class and the Consumer class are passed a reference to the instance of the same Queue class. They use the instance of the Queue class for inter-process communication.

    Here’s what you see when you run this program. Notice that the value placed on the queue by the Publisher is retrieved by the Consumer before the Publisher places the next value on the queue.

    Put: 0
    Get: 0
    Put: 1
    Get: 1
    Put: 2
    Get: 2
    Put: 3
    Get: 3
    Put: 4
    Get: 4
    class Queue {
      
    int exchangeValue;
        boolean busy = false;
        synchronized int get() {
          
    if (!busy)
              try {
                 wait();
              } catch (InterruptedException e) {
                   System.out.println(
                       "Get: InterruptedException");
              }
            System.out.println("Get: " + exchangeValue);
             notify();
          
    return exchangeValue;
        }
        synchronized void put (int exchangeValue) {
          
    if (busy)
              try {
                 wait();
              } catch (InterruptedException e) {
                   System.out.println(
                        "Put: InterruptedException");
              }
           this.exchangeValue = exchangeValue;
          
    busy = true;
           System.out.println("Put: " + exchangeValue);
           notify();
       
    }
    }
    class Publisher implements Runnable {
      
    Queue q;
      
    Publisher(Queue q) {
          this.q = q;
          new Thread (this, "Publisher").start();
      
    }
       public void run() {
          for (int i = 0; i < 5; i++){
             q.put(i);
          }
      
    }
    }
    class Consumer implements Runnable {
      
    Queue  q;
      
    Consumer (Queue  q) {
          this.q = q;
          new Thread (this, "Consumer").start();
      
    }
       public void run() {
          for (int i = 0; i < 5; i++){
             q.get();
          }
      
    }
    }
    class Demo {
      
    public static void main(String args []) {
         Queue q = new Queue ();
         new Publisher (q);
         new Consumer (q);
      
    }
    }


    NOTE:   If your program seems to hang when using two or more threads, you should suspect that a deadlock has occurred. A deadlock occurs when all threads in contention for a resource wait, thinking that another thread is using the resource when actually no thread is using it. Look for code where two threads access two synchronized objects. They could be doing this in an unusual sequence. Redesign your program to avoid this situation. A deadlock can also occur in a rare time-slicing sequence, where the operating system causes a circular dependency of two threads.

    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 5 hosted by Hostway