JAVA多线程问题

kerry803 2005-11-17 05:33:31
题目:设计一个读写者问题的例子。
要求:
* 所有的写者不能同时进入
* 可以有多个读者同时读
* 读者与写者不能同时进入


我已经写了一个程序,代码如下:
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();

}
}


但我觉得这段代码并没有解决“可以有多个读者同时读”的要求,可以帮我完善这个程序吗?谢谢!



...全文
144 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Roy_Sashulin 2005-11-28
  • 打赏
  • 举报
回复
肯定会占CPU时间的。不论怎么读。
kerry803 2005-11-18
  • 打赏
  • 举报
回复
你说的,我知道呀!
我的意思是如何让多个读线程不是独占CPU呢?
Roy_Sashulin 2005-11-17
  • 打赏
  • 举报
回复
楼主请注意:线程并不是同时执行.它只是分配了CPU的时间,让两条线程看起来似乎同时执行.其这它们也是按顺序来运行的.在你的程序中,使用了同步,如:synchronized void put(int i),使用同步的目的在于为了被处理的数据保持正确性,所以它们的运行必然有秩序地处理对象buff1.如果没有,则出来的结果不会是预期的效果.现在有(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();有这么多条线程,速度其实挺慢的.
看一看线程的理论知识.

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧