import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by 32706 on 2016/12/24.
*/
public class ReadThread extends Thread
{
public int id;// 读者ID
//public static int readCount=0;// 读者数量
public static Map<Integer,Integer> readCountMap=new HashMap<>();//存放每一行的读者数量
public static void init_readthread_readcountmap()
{
for(int i=0;i<ReadAndWrite.Value.length;i++)
{
readCountMap.put(i,0);
}
}
public ReadThread(int id)
{
this.id = id;
}
private double get_avrage(int i,int j,int k)
{
double sum=0;
for(int r=j;r<=k;r++)
sum=ReadAndWrite.Value[i][r]+sum;
return sum/(k-j+1);
}
//读者优先
public void run()
{
try{
for(int x=0;x<ReadAndWrite.execute_times;x++)
{
int thread_i=(int)(Math.random()*20)%10;
int thread_j=(int) (Math.random()*200000)%100000;
int thread_k=(int)(Math.random()*200000)%(100000-thread_j)+thread_j;
try
{
//没人在写
if(ReadAndWrite.writeSemaphoreMap.get(thread_i).availablePermits()>0)//可以读
{
System.out.println(id+"号读线程准备读取第"+thread_i+"行的"+thread_j+"=>"+thread_k+"的数据"+" "+ System.currentTimeMillis());
}
else {
System.out.println("有写线程在写操作,"+id+"号线程等待读===="+" "+ System.currentTimeMillis());
}
// 等待着读
ReadAndWrite.readCountSemaphoreMap.get(thread_i).acquire();//如果读者过多则会等待,读者小于5则可以读
if (readCountMap.get(thread_i) == 0)//如果是第i行的第一个读者,那么要考虑是否有写者,没有写者,直接读,有写者,等待写者
{
//此时不能写
int readCount=readCountMap.get(thread_i)+1;// 已经具备读的条件了,读者数量加1
readCountMap.put(thread_i,readCount);
ReadAndWrite.writeSemaphoreMap.get(thread_i).acquire();//上写锁
}
ReadAndWrite.readCountSemaphoreMap.get(thread_i).release();
/**********************************/
//此刻才可以允许其他读者读数据
/**********************************/
ReadAndWrite.readCountSemaphoreMap.get(thread_i).acquire();
//可以读了
System.out.println(id+"号读线程正在读取数据...."+" "+ System.currentTimeMillis());
Thread.sleep((long) (new Random().nextFloat()*1000));
System.out.println(id+"号读线程计算结果为~~~~"+get_avrage(thread_i,thread_j,thread_k)+" "+ System.currentTimeMillis());
//读完了,读者数量减少1
int readCounttem=readCountMap.get(thread_i)-1;
readCountMap.put(thread_i,readCounttem);
if(readCountMap.get(thread_i)==0)//没有读者了,可以写了
{
ReadAndWrite.writeSemaphoreMap.get(thread_i).release();
}
ReadAndWrite.readCountSemaphoreMap.get(thread_i).release();//释放读者信号量
Thread.sleep((long) (new Random().nextFloat()*1000));
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
finally{
ReadAndWrite.Runningthread++;
}
}
}
评论0
最新资源