0

ロックを取得せずに Writer スレッドが不足しているという問題があります。次のコードを見てください。読み取りロックを使用してロックを取得しようとするとtryLock()、ライター プロセスが枯渇し、書き込みができなくなります。公平性があっても、ライター プロセスは完全に枯渇し、決して実行されません。代わりに、試してみるとreader.readLock()、ライタープロセスがロックを取得できます。

何か不足している場合はお知らせください。ライタープロセススレッドは、優先度が高く設定されていても、ロックを取得することはなく、ロックを待っている間にスタックします。

で使えるかどうか誰か教えてtrylock()ください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));

    }
}
4

1 に答える 1