Home arrow Java arrow Page 9 - 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 - 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.


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