【发布时间】:2021-02-11 09:13:52
【问题描述】:
我刚刚写了一个程序,用两个线程轮流打印 0-99。我使用同步块来完成工作。在我的代码中,当我使用“this”作为同步监视器时,程序运行良好。但是当我使用“.class”作为同步监视器时,我得到了IllegalMonitorStateException。谁能告诉我发生了什么?
这是我运行良好的代码
public class WaitTest implements Runnable {
private int n = 0;
@Override
public void run() {
while (true) {
synchronized (this){
notify();
if (n < 100) {
System.out.println(Thread.currentThread().getName() + " " + Integer.toString(n));
++n;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else
break;
}
}
}
public static void main(String[] args) {
WaitTest waitTest = new WaitTest();
Thread threadA = new Thread(waitTest);
Thread threadB = new Thread(waitTest);
threadA.start();
threadB.start();
}
}
这是我遇到异常的代码
public class WaitTest implements Runnable {
private int n = 0;
@Override
public void run() {
while (true) {
synchronized (WaitTest.class){
notify();
if (n < 100) {
System.out.println(Thread.currentThread().getName() + " " + Integer.toString(n));
++n;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else
break;
}
}
}
public static void main(String[] args) {
WaitTest waitTest = new WaitTest();
Thread threadA = new Thread(waitTest);
Thread threadB = new Thread(waitTest);
threadA.start();
threadB.start();
}
}
它们之间唯一的区别是同步后大括号中的内容
【问题讨论】:
标签: java multithreading parallel-processing thread-safety