Java
  Home arrow Java arrow Page 2 - 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 - Stopping and Synchronization
    ( Page 2 of 4 )

     

    We covered earlier that threads must be started with the start() method. Failing to do so and then running them via run() results in a sequential execution and not what we want, which is multi-threading: simultaneous execution of multiple threads. All right but one might also ask, how do we stop a thread that is running? 

    There’s a method called stop() that does that—however, its use isn’t advised. That is because there’s a chance it might hog the execution, dragging the system into a stale mate or dead point. The stop() method does not free up allocated system resources. Fortunately, there is a simple and effective workaround. We’re going to introduce a boolean variable (attribute) that always refers to the state of the thread. 

    Let’s call it isRunning. We declare this as an attribute of the class with the following modifiers: private volatile. At first, surely, this variable starts out as true. However, we will write a method that sets this to false, such as the stopping() thread. Right after that, we can easily modify the run() method so that it runs while isRunning is true.

     

    class MyThread extends Thread{

    private volatile boolean isRunning = true;

     

    public void stopping(){

    isRunning = false;

    }

     

    public void run(){

    while (isRunning){

    // action goes here

    try{

    sleep(10);

    }

    catch (InterruptedException e){}

    }

    }

    Based on the above source code, threads can be stopped by calling the stopping() method instead of the inherited stop(), which might cause problems. This is much safer. 

    And finally, the time has come for us to talk about synchronization. It is one of the most important concepts when working with multiple threads within an application. In order to fully grasp the concept of synchronized execution, we’re required to also talk about unsynchronized (asynchronous) execution. 

    If we don’t explicitly “synchronize” the execution of threads, then by all norms they're executed asynchronously. This kind of multi-threading isn’t reliable because it does not give consistent results. A so-called “race condition” appears, which means the threads are “racing each other” because some operations can be completed faster than others, the processor might have faster access to some data (registers), and so forth. 

    Moreover, this also means that executing the same application another time does not yield the same results with a 100% guarantee. By definition, a thread becomes synchronized if you become the owner of its object monitor. This is somewhat similar to locking the object. And you can do this in two possible ways. 

    Each time the program enters a synchronized method, it becomes owner of that object’s monitor (or class monitor in the case of static methods). In a nutshell, this locks the thread’s access to the synchronized method if another thread is already executing it. And this blockage applies until the lock is released by exiting the method or invoking the wait() method. The latter wait() temporarily releases the monitor. 

    You can make a method synchronized by adding the “synchronized” keyword prior to its declaration. This is the first solution. Another way to make a thread become owner of its object monitor is by using the “synchronized” statement on a common object. The latter is safer because it always releases the lock once the execution is done.

    Consider the following example for the synchronized method path.

     

    synchronized void func(...){

    ...

    }

     

    And now let’s see another example for the synchronized common object solution.

     

    void func(...){

    // ...

    synchronized(obj){

    // ...

    }

    }

     

    On the next page we’ll tackle inter-thread communication and present an example of the popular producer-consumer model. That problem pops up very frequently as an approach used by professors to explain how inter-thread communication is applied. 



     
     
    >>> 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 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek