Tech I Enjoy Logo

Custom Search




  Home >> Java

Java-based multiple thread example on using wait, notify and notifyAll
on the synchronized common/shared object among threads.

Let us have a common class with two instance variables, such as i and j

CommonObject.java
class CommonObject {
  int i;
  int j;
  public int add() {
    return i+j;
  }
}
This class has a method "add" that uses these two instance variables and returns the sum of values of these two variables. There is this runnable class that will be used within two Thread classes in order to show the effect of synchronized block on the common object. ComputerService.java
class ComputerService implements Runnable {
    CommonObject co;
    int[] a;
    int[] b;
    public Computer(CommonObject co, int[] a, int[] b) {
      this.co = co;
      this.a = a;
      this.b = b;
    }
    public void run() {
      try {
          System.out.println("Thread :"+Thread.currentThread());
          synchronized(co) {
          for(int i=0;i<a.length;i++) {
           co.notify();
           co.i = a[i];
           co.j = b[i];
           System.out.println("Thread :"+Thread.currentThread()+"   "+co.add());
           co.wait();
          }
          co.notifyAll();
         }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
}
Following is the test client program in order to test these multi-threading program with some dummy values. ThreadTest.java
public class ThreadTest {
  public ThreadTest() {
    CommonObject co = new CommonObject();
    Thread t1 = new Thread(new ComputerService(co,
                             new int[]{5,10,15,20,25,30},
                             new int[]{5,10,15,20,25,30}));
    Thread t2 = new Thread(new ComputerService(co,
                             new int[]{5,10,15,20,25,30},
                             new int[]{5,10,15,20,25,30}));
    t1.start();
    t2.start();

  }
  public static void main(String[] args) {
    new ThreadTest();
  }
}
In the above test program we are providing arrays of values of type int to the runnable instance, and the common object instance with the logic for adding these int values, sequentially one after another. While running this ThreadTest test harness/code, following is the console output: Thread :Thread[Thread-0,5,main] <- Here the thread 1 enters the synchronized block Thread :Thread[Thread-0,5,main] 10 <- T1 prints out the sum of two values from two arrays and calls wait on the synchronized common object. This causes thread 1 to lose the monitor of synchronized object, and gives the other thread 2 to acquire the lock. Thread :Thread[Thread-1,5,main] <- Here thread 2 enters the synchronized block Thread :Thread[Thread-1,5,main] 10 <- T2 prints out the sum value of two values from two arrays Thread 2 calls wait and then notify method on the share object and making the other thread T1 (that is waiting to acquire lock for the common synchronized instance) to start processing. And this goes on till all the array elements are used. Thread :Thread[Thread-0,5,main] 20 Thread :Thread[Thread-1,5,main] 20 Thread :Thread[Thread-0,5,main] 30 Thread :Thread[Thread-1,5,main] 30 Thread :Thread[Thread-0,5,main] 40 Thread :Thread[Thread-1,5,main] 40 Thread :Thread[Thread-0,5,main] 50 Thread :Thread[Thread-1,5,main] 50 Thread :Thread[Thread-0,5,main] 60 Thread :Thread[Thread-1,5,main] 60 notifyAll method call will have both these thread to be notifies and exit the mail program as a consequence, or else both these threads will hang up for ever waiting for the lock. Now just for the sake of experimenting, try commenting wait, notify method calls from the ThreadTest program, and one can find that both threads go selfish and not allow co-execution of both threads, thus making one thread completes its operations, before allowing other thread to execute. If anything missed out , please let me know at techienjoy at yahoo . com
Example of Drag and Drop using Java Technology :
Example of Drag and Drop using Java Technology.
Image creation using Java AWT :
In-Memory Image creation using AWT on Java Platform.
Synchronized Block wait and notify With Example :
Example using wait and notify from within
synchronized block with code and explained
RMI and Java Stub and Skeleton :
Example using RMI using Java Technology.
Thread wait and notify With Example :
Example using wait and notify within Thread 
with code and explained
Thread Deadlock using Java :
Example reproducing a possible Thread 
using Java Technology.
Example ThreadPoolExecutor using Java :
ThreadPoolExecutor Example using Java Technology.
Java Reflection using Comparator :
Comparator using Reflection on Java Platform
and example discussed.
Thread design scenario using Java :
Thread design scenario using Java Technology.
Interview Questions and answer of Java Technology :
Interview Questions and answer of Java Technology.
List of Examples on Java Platform :
List of Examples on Java Platform.
Event Handling using Java Technology :
Example on how to use Event
and handling code using Java Technology.


References :
Tags: java comparator reflection
Tags: java example drag n drop
Tags: Java Interview Questions
Tags: java rmi tutorial stub skeleton
Tags: Java Thread Deadlock
Tags: Java Thread Design Scenarios
Tags: Java threadpoolexecutor
Tags: Java



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions