JAVA多线程问题
题目:设计一个读写者问题的例子。
要求:
* 所有的写者不能同时进入
* 可以有多个读者同时读
* 读者与写者不能同时进入
我已经写了一个程序,代码如下:
class buff1
{
static int value[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static int rc;
static int j;
private boolean w=false;
synchronized void put(int i)
{
while(rc!=0)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
w=true;
value[j]=i;
j=j+1;
//w=true;
notify();
}
synchronized void get()
{
while(j==0)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
//w=false;
rc=rc+1;
notifyAll();
//return j;
}
}
class writer extends Thread
{
private buff1 bf;
public writer(buff1 bf)
{
this.bf=bf;
}
public void run()
{
//System.out.println("aa"+i);
try{
sleep(1);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
synchronized(bf)
{
int i=(int)(Math.random()*100);//产生随机写入的数
bf.put(i);
System.out.println("writer "+getName()+"is writing..."+i);
//System.out.println("reader :"+i);
System.out.println("writer "+getName()+" has written over!");
}
/* try{
sleep(12);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}*/
}
}
class reader extends Thread
{
private buff1 bf;
public reader(buff1 bf)
{
this.bf=bf;
}
public void run()
{
bf.get();
synchronized(bf)
{
System.out.println("reader "+getName()+" is reading...");
for(int j=0;j<buff1.j;j++)
System.out.println("reader "+getName()+" is reading "+buff1.value[j]);//读出到目前为止已经写入的数
System.out.println("reader "+getName()+" has read over!");
buff1.rc=buff1.rc-1;
//System.out.println(buff1.rc);
}
/*try{
sleep(100);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}*/
}
public static void main(String args[])
{
buff1 bf=new buff1();
//for(int k=0;k<4;k++)
//(new reader(bf)).start();
(new writer(bf)).start();
(new writer(bf)).start();
(new writer(bf)).start();
(new reader(bf)).start();
(new writer(bf)).start();
(new reader(bf)).start();
(new reader(bf)).start();
}
}
但我觉得这段代码并没有解决“可以有多个读者同时读”的要求,可以帮我完善这个程序吗?谢谢!