我遇到了 Writer 线程在没有锁的情况下被饿死的问题。请看下面的代码。如果我试图获取tryLock()
用于读取锁的锁,写入器进程将变得饥饿并且永远无法写入。即使公平,编写程序也会完全饿死并且永远不会执行。相反,如果我只尝试,reader.readLock()
那么编写器进程将能够获得锁。
如果我遗漏了什么,请告诉我,即使它设置为高优先级,编写器进程线程也永远不会获得锁并且会卡住等待锁。
谁能告诉我是否可以使用trylock()
with ReadWriteLocks
。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.*;
class ReadWrite{
private int a, j=0,k =0;
private final ReentrantReadWriteLock asd = new ReentrantReadWriteLock();
private final Lock readlock = asd.readLock();
private final Lock writelock = asd.writeLock();
ReadWrite(){
a = 0 ;
}
ReadWrite(int a){
this.a = a;
}
public int read() {
try {
if (readlock.tryLock())
{
//readlock.lock();
k = k + 1;
if (k%100000==0) {
System.out.println("read " + k + " times ==> Written " + j + " times");
}
readlock.unlock();
return a;
}
}
catch(Exception E) {
System.out.println(E);
return a;
}
return 0;
}
public void write(int a) {
int k = 9;
try {
writelock.lock();
//writelock.lock();
this.a = a;
k = 0;
j = j + 1;
System.out.println("Acquored");
}
catch(Exception E) {
System.out.println(E);
}
finally {
if (k == 0 )
writelock.unlock();
}
}
}
class reader implements Runnable{
ReadWrite a;
reader(Object b){
a = (ReadWrite) b;
}
public void run() {
while(true) {
try{a.read();
//Thread.sleep(100);
}
catch(Exception E) {
}
}
}
}
class writer implements Runnable{
ReadWrite a;
writer(Object b){
a = (ReadWrite) b;
}
public void run() {
//Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
while(true) {
try {
//Thread.sleep(1);
}
catch(Exception E) {
}
a.write((int) Math.ceil(Math.random()*100));
}
}
}
class Practice{
public static void main(String args[]) {
ReadWrite a = new ReadWrite();
System.out.println("Invoking Write Thread");
ExecutorService asd = Executors.newFixedThreadPool(100);
asd.execute(new writer(a));
for (int i = 0 ; i < 98 ; i ++)
asd.execute(new reader(a));
}
}