gpt4 book ai didi

java - NotifyAll,IllegalMonitorStateException

转载 作者:搜寻专家 更新时间:2023-11-01 01:20:49 26 4
gpt4 key购买 nike

import java.math.BigInteger;

class Numbers {

final static int NUMBER = 2;
final static int POWER = 4;

static long msecs;
static BigInteger result;
static Boolean done = false;

public static void main(String[] args) {

BigInteger number = BigInteger.valueOf(NUMBER);
result = number;

//Boolean done = false;

Runnable pow = () -> {
System.out.println(number + " pow " + POWER + " = " + number.pow(POWER));

synchronized (done) {
done = true;
done.notifyAll();
}
};

Runnable sum = () -> {
for(int i = 2; i<POWER; i=i*i) {
result = result.multiply(result);
}

System.out.println(number + " sum " + POWER + " = " + result);

synchronized (done) {
done = true;
done.notifyAll();
}
};

Runnable time = () -> {
for(msecs = 0; true; msecs++) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
//nic
}
}
};

Thread timet = new Thread(time);
Thread sumt = new Thread(sum);
Thread powt = new Thread(pow);

timet.start();
powt.start();

synchronized (done) {
while(!done) {
try {
done.wait();
} catch (InterruptedException e) {
//nic
}
}
}

timet.interrupt();
powt.interrupt();

System.out.println("Pow time " + msecs + " msecs.");
done = false;

timet.start();
sumt.start();

try {
synchronized (done) {
while (!done) {
done.wait();
}
}
} catch (InterruptedException e) {
//nic
}


timet.interrupt();
sumt.interrupt();

System.out.println("Sum time " + msecs + " msecs.");

}
}

我想检查这两种方法之间的时间差异,但是 done.notifyAll() 一直抛出 IllegalMonitorStateException

最佳答案

问题在这里:

synchronized (done) {
done = true;//<---problem
done.notifyAll();
}

由于您正在为 done 分配新值,这意味着您正在 Boolean.TRUE 上执行 notifyAll 但您的同步块(synchronized block)正在使用监视器 boolean 值.FALSE。由于 notifyAll 要求线程拥有对其执行的对象的监视器,因此它会抛出 IllegalMonitorStateException

所以不要更改同步对象的值。还要避免同步可用于所有类的对象(公共(public)常量/文字),因为您冒着其他人会有相同想法并且也会在他们的同步中使用它们的风险,这可能会给您带来一些痛苦。

锁应该只能从它们所属的类中访问。因此,以 Jon Skeet (What is the difference between synchronized on lockObject and using this as the lock?) 为例并自行同步

private final Object lock = new Object();

关于java - NotifyAll,IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com