关于超类字段的Java wait()和notify()

时间:2017-08-31 08:39:26

标签: java multithreading inheritance

我正在处理几个需要多线程使用的类。由于访问模式相同但它们使用不同的数据结构,因此我将访问模式提取到超类,并使用其方法来管理访问,而子类只是管理数据结构。只要我使用synchronized块(甚至是单wait s),它就可以正常工作,但当我尝试引入notifynotifyAll指令时,它开始投掷{{ 1}} S上。

我的超类:

IllegalMonitorStateException

我对此的典型用法是:

public abstract class SyncObject {
    protected Integer readLock;
    protected Boolean writeLock;

    public SyncObject(){
        this.readLock = 0;
        this.writeLock = false;
    }

    protected void acquireReadLock(){
        boolean hasBeenInterrupted = false;
        synchronized (this.writeLock){
            while(this.writeLock)
                try {
                    this.writeLock.wait();
                } catch (InterruptedException e) {
                //We can't leave the locks in a non-consistent state, so the interruption is swallowed
                //Once the lock have been set the interruption flag is set again to true, in case we need
                // it later
                    hasBeenInterrupted = true;
                }

            synchronized (this.readLock){
                this.readLock++;
            }
        }

        if(hasBeenInterrupted){
            Thread.currentThread().interrupt();
        }
    }

    protected void releaseReadLock(){
        synchronized (this.readLock){
            this.readLock--;
        }
    }

    protected void acquireWriteLock(){
        boolean hasBeenInterrupted = false;
        synchronized (this.readLock){
            synchronized (this.writeLock){
                while(this.readLock > 0)
                    try {
                        this.readLock.wait();
                    } catch (InterruptedException e) {
                        //See above
                        hasBeenInterrupted = true;
                    }

                while(this.writeLock)
                    try {
                        this.writeLock.wait();
                    } catch(InterruptedException e) {
                        //See above
                        hasBeenInterrupted = true;
                    }

                this.writeLock = true;
            }
        }

        if(hasBeenInterrupted){
            Thread.currentThread().interrupt();
        }
    }

    protected void releaseWriteLock(){
        synchronized (this.writeLock){
            this.writeLock = false;
        }
    }
}

如果我复制超类'我的classess中的方法工作正常,但有没有办法从超类中管理所有内容(从而避免在多个类中复制相同的代码)?

0 个答案:

没有答案