}
//封装的业务类
class Business{
private int data=0; //共享资源属性
private int readThreads = 0; //读线程数
//private boolean isWriting = false;
//是否执行写 后来发现不需要 当write抢占锁时 所有的read 都被挡在synchronized (this){}之上 无机会执行wait
public void read(){
synchronized (this) {
/*while(isWriting){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
//readThreads不被锁的话 会出现read和write不互斥的小概率事件 导致线程不安全
readThreads++;
}
System.out.println(Thread.currentThread().getName()+" read begin");
System.out.println(Thread.currentThread().getName()+" read:"+data);
System.out.println(Thread.currentThread().getName()+" read finish");
synchronized (this) {
readThreads--;
this.notifyAll();
}
}
public synchronized void write(int i){
while(readThreads != 0){//当read 正处于do something状态时 来个write 那就只有等等先了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//isWriting = true;
System.out.println(Thread.currentThread().getName()+" write start");
data = i;
System.out.println(Thread.currentThread().getName()+" write:"+i);
System.out.println(Thread.currentThread().getName()+" write over");
//isWriting = false;
this.notifyAll();
}
}
思考中:
5.当读频繁时 readThreads会长时间!= 0 写线程会饿死 这个可以如何解决?
摘自 Goodspeed85