what' wrong with my simple codes on reader/writer problem ,the writer thread never run

D

DaVinci

The Problem is the writer never had changes to run?
but ,why?
Thanks.
Codes:
import java.awt.*;
import java.util.concurrent.locks.*;
public class Main
{

public static void main(String[] args)
{
init();
for(int i = 0;i< readers.length;i++)
{
readers.start();
}

for(int j = 0;j<writers.length;j++)
{
writers[j].start();
}

}
public static void init()
{
int nr = 5;
readers = new Reader[nr];
for(int i = 0;i < nr ;i++)
{
Reader reader = new Reader(i);
readers = reader;
}
//----------------------------
int nw = 3;
writers = new Writer[3];
for(int i = 0;i< nw;i++)
{
Writer writer = new Writer(i);
writers = writer;
}
};
static class Reader extends Thread
{
public Reader(int num)
{
numOfReader = num;
}
public void run()
{
while(true)
{
reading();
}

}
public void reading()
{
r.lock();
try
{
System.out.println("reader "+numOfReader+" is
reading ");

this.sleep(TIMEOFWORK);

}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{

r.unlock();
}

}
private int numOfReader;

};

static class Writer extends Thread
{
public Writer(int num)
{
numOfWriter = num;
}
public void run()
{
while(true)
{
writing(); //???
}
}
public void writing()
{
w.lock();
try
{

numOfWriter ++;
System.out.println("writer "+numOfWriter+" is writing");

this.sleep(TIMEOFWORK);


}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
w.unlock();
}

}
private int numOfWriter;

};

public static final ReentrantReadWriteLock rwl = new
ReentrantReadWriteLock();
public static final Lock r = rwl.readLock();
public static final Lock w = rwl.writeLock();

public static Reader[] readers;
public static Writer[] writers;
public static final int TIMEOFWORK = 2000;

}
 
P

Piotr Kobzda

DaVinci said:
The Problem is the writer never had changes to run?
but ,why?

The writer have a chance to run, but most often loses in unfair
competition. Use of the ReentrantReadWriteLock constructed as fair
should help.


piotr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top