Searching...
Tuesday, 30 April 2013

wait() and notify() Simple example

23:07

Wait and notify example

wait()-Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

notify()-Wakes up a single thread that is waiting on this object's monitor.

Example

Here is one simple example to use wait and notifiy methods. In this example there are two threads using the same resource (ArrayList) to add and remove objects. The removeThread will wait until the records in to the arrayList. Addrecord thread will notify once the addition is done.

package com.vinod.test;

import java.util.ArrayList;
import java.util.List;

public class ConcurrentTest {
public static void main(String[] args) {
final List<String> students = new ArrayList<String>();
Thread addRecord = new Thread() {
public void run() {
System.out.println("Addrecord thread started");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
synchronized (students) {
System.out.println("Now thread 1 locked student arraylist and adding student details");
// adding elements to students
students.add("Pretech");
System.out.println("students details added by thread1" + students);
students.notify();

}
}
};

Thread removeRecord = new Thread() {
public void run() {
System.out.println("removerecord thread started");
synchronized (students) {
System.out.println("Now thread 2 locked student arraylist");
// if students list is empty it will wait until getting data
if (students.isEmpty()) {
try {
students.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// removing record
System.out.println("Removing item " + students.get(0));
students.remove(0);
}
System.out.println("students details after removing by thread2" + students);
}

}
};
addRecord.start();
removeRecord.start();
}

}

Output

removerecord thread started
Now thread 2 locked student arraylist
Addrecord thread started

0 comments: