Hi jeroen:
Few comments regarding your code:
In class Queue:-
private LinkedList list = new Vector();
do not instantiate a Vector and assign it to a LinkedList Reference
it will give a compilation error
Instead use one of the following:-
1. Linkedlist ll=new LinkedList(); --OR--
2. List l=new LinkedList();
in class ThreadOne and ThreadTwo
Instantiate the queue object else you will get a compilation error
in class ThreadOverall:
Synchronization is used to allow only one thread to access a particular Queue object. In your current implementation,
both the ThreadOne instance and ThreadTwo instance access 2 different instances of the Queue object, so you are actually
not using synchronization.
To explain the same example in a simpler way, I have modified your programs as follows.
1. Like before ThreadOverall contains the main() class that instantiates the thread objects and starts them
2. ThreadOne is the class that writes data to the list and notifies any object waiting on the list that the lock for the list object is availible
3. ThreadTwo is the class that waits for ThreadOne to write the data into the list, only after ThreadOne is done writing the data, ThreadTwo is notified and it reads the contents of the list.
I hope that it helps. Below are the modified programs.
package waitNotify;
import java.util.LinkedList;
/*main class that instantiates the threads and starts them*/
public class ThreadOverall
{
public static void main(
String args[])
{
LinkedList list=new LinkedList();
/*Both one and two are trying to access the same Queue object*/
ThreadOne one = new ThreadOne(list);
ThreadTwo two = new ThreadTwo(list);
two.start();
one.start();
}
}
-----------
package waitNotify;
import java.util.LinkedList;
/**
* This class writes the data to the list, once it is done writing
*/
public class ThreadOne extends Thread {
LinkedList list;
public ThreadOne(LinkedList ll) {
list = ll;
}
/**
* DOCUMENT ME!
*/
public void run() {
//once lock on queue object availible, get the lock on it
synchronized (list) {
// thread is eligible to run but if lock on queue not availible wait() on the queue object
System.out.println("writing data...");
for (int i = 0; i < 10; i++) {
list.add(new Integer(i).toString());
}
list.notify();
}
}
}
---------
package waitNotify;
import java.util.LinkedList;
import java.util.ListIterator;
/**This class reads the data in the linked list, it waits for the writing thread,
* once it is notified, it starts reading and displays the contents of the list
* */
public class ThreadTwo extends Thread {
LinkedList list;
public ThreadTwo(LinkedList ll) {
list =ll;
}
public void run() {
synchronized (list) {
try {
System.out.println("Waiting to read...");
list.wait();
} catch (InterruptedException ie) {
System.out.println("notification...");
}
System.out.println("reading data...");
ListIterator li=list.listIterator();
while(li.hasNext())
{System.out.println(li.next());}
}
}
}
Regards