Java
  Home arrow Java arrow Page 3 - More About Multithreading in Java
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
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? 
Google.com  
JAVA

More About Multithreading in Java
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2009-03-04


    Table of Contents:
  • More About Multithreading in Java
  • Stopping and Synchronization
  • Inter-Thread Synchronization and Communication
  • Taking a Break

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    More About Multithreading in Java - Inter-Thread Synchronization and Communication
    ( Page 3 of 4 )

     

    Inter-thread communication is all about making synchronized threads communicate with each other. Sometimes one might want to pause (or delay) the execution of a thread until some condition is met. And this condition only occurs if another thread does such and such. To implement these, inter-thread communication is necessary.

    Java offers three possible solutions. The following three methods are inherited from the Object class: public final void wait(), public final void notify(), public final void notifyAll(). The first method forces a thread to wait until some other thread calls either notify() or notifyAll() methods. The second notify() method wakes up the thread that invoked the wait() method on the same object. And the third method, notifyAll(), wakes up all of the threads that called the wait() method on the same object. 

    As mentioned earlier, wait() is defined in the Object class, and it can only be called from a synchronized thread. It may throw an InterruptedException. In short, it releases the lock it is holding on an object’s monitor, thereby allowing other threads to run. The notify() method wakes up any of the threads that are waiting to release the object’s monitor lock. This choice is arbitrary and at the discretion of the JVM. 

    The awakened threads will resume execution right from where they were paused. The same applies to notifyAll(). Now let’s explain the producer-consumer model. Imagine the shelf of a bookstore, for example. The producer places books on the shelf, while the consumer grabs them. There are two conditions necessary. First, there should be books on the shelf for the consumer to grab. And second, if there are too many books on the shelf, then there isn't any space left for more books. 

    The producer and consumer model consists basically of two synchronized threads that should communicate with each other. It’s not that hard at all, but if it is neglected, the results can be disastrous. So this problem is going to implement two of the major concepts we have learned in this article: thread synchronization and inter-thread communication. All right, so let’s begin writing the code!

     

    public class Books{

    private int count;

    private boolean isReady = false;

     

    public synchronized int grab(){

    while (isReady == false){

    try{

    wait();

    }

    catch (InterruptedException e){}

    }

    isReady = false;

    notifyAll();

    return count;

    }

     

    public synchronized void place(int newCount){

    while (isReady == true){

    try{

    wait();

    }

    catch (InterruptedException e){}

    count = newCount;

    isReady = true;

    notifyAll();

    }

    }

    }

     

    And now the implementation of the Producer class:

     

    public class Producer extends Thread{

    private Books myShelf;

    private int number;

     

    public Producer(Books b, int number){

    myShelf = b;

    this.number = number;

    }

     

    public void run(){

    for (int i = 0; i < 5; ++i){

    myShelf.place(i);

    System.out.println("Prod No#: " + this.number + " places " +i);

    try{

    sleep(10);

    }

    catch (InterruptedException e){}

    }

    }

    }

     

    Finally, here comes the Consumer class as well. Check it out below.

     

    public class Consumer extends Thread{

    private Books myShelf;

    private int number;

     

    public Consumer(Books b, int number){

    myShelf = b;

    this.number = number;

    }

     

    public void run(){

    int val = 0;

    for (int i = 0; i < 5; ++i){

    val = myShelf.grab();

    System.out.println("Cons No#: " + this.number + " grabs " +val);

    }

    }

    }

     

    All that is left is creating a class with public static void main, so that we can launch this application. The last snippet is below.

     

    public class MyClass{

    public static void main (String args[]){

    Books b = new Books();

    Producer p = new Producer (b, 1);

    Consumer c = new Consumer (b, 1);

     

    p.start();

    c.start();

    }

    }

     

    And finally, here’s the attached output. Check it out. And we’re done for now!

     

    Prod No#: 1 places 0

    Cons No#: 1 grabs 0

    Prod No#: 1 places 1

    Cons No#: 1 grabs 1

    Prod No#: 1 places 2

    Cons No#: 1 grabs 2

    Prod No#: 1 places 3

    Cons No#: 1 grabs 3

    Prod No#: 1 places 4

    Cons No#: 1 grabs 4



     
     
    >>> More Java Articles          >>> More By Barzan "Tony" Antal
     

       

    JAVA ARTICLES

    - Exception Handling Techniques in Java
    - More About Multithreading in Java
    - The Basics of Multiple Threads in Java
    - Data Access Using Spring Framework JDBC
    - New Object Initialization in Java
    - Adding Images With iTextSharp
    - Adding Columns With iTextSharp
    - Creating Simple PDF Files With iTextSharp
    - The Spring Framework: Understanding IoC
    - Introducing the Spring Framework
    - Java Classes
    - Completing the Syntactic Comparison of Java ...
    - Syntactic Comparison of Java and C/C++
    - Java Statements
    - Conditionals, Expressions and Other Java Ope...





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