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
分配新值,这意味着您正在 notifyAll
上执行 Boolean.TRUE
但您的同步块(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();