Home arrow Java arrow Page 10 - Multithreading in Java
JAVA

Multithreading in Java


Multithreading allows two parts of the same program to run concurrently. This article discusses how to pull off this performance-improving feat in Java. It is excerpted from chapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 535
August 04, 2005
TABLE OF CONTENTS:
  1. · Multithreading in Java
  2. · Overhead
  3. · The Thread Classes and the Runnable Interface
  4. · Creating Your Own Thread
  5. · Creating a Thread by Using extends
  6. · Using isAlive() and join()
  7. · Setting Thread Priorities
  8. · Synchronizing Threads
  9. · Using the Synchronized Statement
  10. · Suspending and Resuming Threads

print this article
SEARCH DEVARTICLES

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.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials