java同步对象vs同步这个

时间:2022-10-11 06:51:14

i want to write own simple semaphore and done it as follows:

我想写自己的简单信号量,并按如下方式完成:

class Semaphore {
    private boolean done;
    private final Object lock = new Object();

    public Semaphore(boolean done){ this.done = done;}

    public void acquire() throws InterruptedException {
        synchronized (lock) {
            while (!done)
                lock.wait();

            done = false;
        }
    }

    public void release() {
        synchronized (lock) {
            done = true;
            lock.notify();
        }
    }
}

it works fine. But if i replace synchronized (lock) with synchronize (this) it begins to throw IllegalMonitorStateException. Why so?

它工作正常。但是如果我用同步(this)替换synchronized(lock),它就会开始抛出IllegalMonitorStateException。为什么这样?

1 个解决方案

#1


2  

As @Alexei Kaigorodov mentioned in comment, when you replace synchronized (lock) with synchronize (this). Then, you need to also replace lock to this in your code.

正如@Alexei Kaigorodov在评论中提到的,当你用同步(this)替换synchronized(lock)时。然后,您还需要在代码中将lock替换为this。

As this indicate to current object which is different than lock object.

这表示当前对象与锁定对象不同。

Now, you replaced synchronized (lock) with synchronize (this) which means now you are trying to acquire lock on current object but you were waiting on object of Object class.

现在,您使用synchronize(this)替换了synchronized(lock),这意味着您现在尝试获取当前对象的锁定,但是您正在等待Object类的对象。

This works absolutely fine :

这非常好:

public void acquire() throws InterruptedException {
    synchronized (this) {
        while (!done)
            this.wait();

        done = false;
    }
}

public void release() {
    synchronized (this) {
        done = true;
        this.notify();
    }
}

#1


2  

As @Alexei Kaigorodov mentioned in comment, when you replace synchronized (lock) with synchronize (this). Then, you need to also replace lock to this in your code.

正如@Alexei Kaigorodov在评论中提到的,当你用同步(this)替换synchronized(lock)时。然后,您还需要在代码中将lock替换为this。

As this indicate to current object which is different than lock object.

这表示当前对象与锁定对象不同。

Now, you replaced synchronized (lock) with synchronize (this) which means now you are trying to acquire lock on current object but you were waiting on object of Object class.

现在,您使用synchronize(this)替换了synchronized(lock),这意味着您现在尝试获取当前对象的锁定,但是您正在等待Object类的对象。

This works absolutely fine :

这非常好:

public void acquire() throws InterruptedException {
    synchronized (this) {
        while (!done)
            this.wait();

        done = false;
    }
}

public void release() {
    synchronized (this) {
        done = true;
        this.notify();
    }
}