Java
  Home arrow Java arrow Page 10 - 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 - Suspending and Resuming Threads


    (Page 10 of 10 )

    There might be times when you need to temporarily stop a thread from processing and then resume processing, such as when you want to let another thread use the current resource. You can achieve this objective by defining your own suspend and resume methods, as shown in the following example.

    This example defines a MyThread class. The MyThread class defines three methods: the run() method, the suspendThread() method, and the resumeThread() method. In addition, the MyThread class declares the instance variable suspended, whose value is used to indicate whether or not the thread is suspended.

    The run() method contains a for loop that displays the value of the counter variable. Each time the counter variable is displayed, the thread pauses briefly. It then enters a synchronized statement to determine whether the value of the suspended instance variable is true. If so, the wait() method is called, causing the thread to be suspended until the notify() method is called.

    The suspendThread() method simply assigns true to the suspended instance variable. The resumeThread() method assigns false to the suspended instance variable and then calls the notify() method. This causes the thread that is suspended to resume processing.

    The main() method of the Demo class declares an instance of MyThread and then pauses for about a second before calling the suspendThread() method and displaying an appropriate message on the screen. It then pauses for about another second before calling the resumeThread() method and again displaying an appropriate message on the screen.

    The thread continues to display the value of the counter variable until the thread is suspended. The thread continues to display the value of the counter variable once the thread resumes processing. Here’s what is displayed when you run this program:

    Thread: 0
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Thread: Suspended
    Thread: Resume
    Thread: 5
    Thread: 6
    Thread: 7
    Thread: 8
    Thread: 9
    Thread exiting.
    class MyThread implements Runnable {
      String name;
      Thread t;
      boolean suspended;
      MyThread() {
        
    t = new Thread(this, "Thread");
         suspended = false ;
         t.start();
     
    }
      public void run() {
         try {
           
    for (int i = 0; i < 10; i++) {
               System.out.println("Thread: " + i ); 
               Thread.sleep(200);
               synchronized (this) {
                 
    while (suspended) {
                     wait();
                  }
               }
            }
         } catch (InterruptedException e ) {
             
    System.out.println("Thread: interrupted.");
         }
         System.out.println("Thread exiting.");
     
    }
      void suspendThread() {
        
    suspended = true;
      }
      synchronized void resumeThread() {
        
    suspended = false;
         notify();
     
    }
    }
    class Demo {
      
    public static void main (String args [] ) {
          MyThread t1 = new MyThread();
          try{
            
    Thread.sleep(1000);
             t1.suspendThread();
             System.out.println("Thread: Suspended"); 
             Thread.sleep(1000);
             t1.resumeThread();
             System.out.println("Thread: Resume");
           } catch ( InterruptedException e) {
           }
           try {
             
    t1.t.join();
           } catch ( InterruptedException e) {
                System.out.println (
                     "Main Thread: interrupted");
           }
       }
    }

    Quiz
    1. What is a thread?

    2. What is multitasking?

    3. What kind of overhead occurs during multitasking?

    4. What is a thread priority?

    5. What is synchronization?

    6. What is the Runnable interface?

    7. When should you extend the Thread class?

    8. If you create one thread in your program, how many threads actually run?

    9. What method must you override when you create a thread in your program?

    10. How do you define the portion of your program that becomes a thread?

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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