Hi,
please go through this code which i guess is a solution to what you are asking.
Basically what this does is:
1. Mutual exclusive between reader and writer threads is acheived with the 'flag' object.
2. Before reader or writer can have access to the 'data', they check for 'flag' value. (only if flag = reader, reader threads can proceed, only if flag = writer, writer thread can proceed).
Otherwise they block there, and the one which could proceed and obtain access to the data, will wake the waiting threads. As soon as a reader/writer thread wakes up, they set the falg to its type.
4. The reader threads are allowed to access data simultaneosly.
5. Writer threads can modify data one at a time.
------------------------------------------------------
public class Main
{
private int data = 0;
private
String flag = "writer";
public Main()
{
}
public static void main(String[] a)
{
Main m = new Main();
}
class Writer extends Thread
{
private int name;
public Writer(int name)
{
this.name = name;
}
public void run()
{
synchronized(flag)
{
if(flag.equals("reader"))
{
try { flag.wait(); } catch(Exception e) {}
}
flag = "writer";
}
writeData();
synchronized(flag)
{
flag.notifyAll();
}
}
private synchronized void writeData()
{
data+=1;
System.out.println("Writer thread:"+name+" wrote data="+data);
}
}
class Reader extends Thread
{
private int name;
public Reader(int name)
{
this.name = name;
}
public void run()
{
synchronized(flag)
{
if(flag.equals("writer"))
{
try{ flag.wait(); } catch(Exception e) {}
}
flag = "reader";
}
readData();
synchronized(flag)
{
flag.notifyAll();
}
}
private void readData()
{
System.out.println("Data="+data+" from Reader thread:"+name);
}
}
}
------------------------------------------
Hope this helps.
thanks,
Sony Gam