【发布时间】:2018-03-07 22:50:28
【问题描述】:
这是我的第一篇文章,如果我做错了什么,请见谅。 我试图了解 Java 中的线程是如何工作的,特别是同步,这就是为什么我创建了一小段代码,它应该打印 1、2、3、4、5、6(在一个线程中)然后第二个线程等待第一个完成,然后打印 6,5,4,3,2,1 但它只执行前 6 个步骤并告诉我线程 t2 中的等待方法存在监视器问题和问题通知所有线程 t1。也许我对对象的同步一无所知。这是我的代码:
public class anObject extends Thread {
long value;
String name;
public anObject(long value, String name) {
this.value = value;
this.name = name;
}
public synchronized void add() {
this.value++;
}
public synchronized void sub() {
this.value--;
}
public static void main(String[] args) {
anObject il = new anObject(0, "Bob");
synchronized (il) {
Thread t1 = new Thread(il) {
public void run() {
while (il.value > 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 6; i++) {
il.add();
System.out.println(il.value);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
il.notifyAll();
}
};
Thread t2 = new Thread(il) {
public void run() {
while (il.value < 6) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 6; j++) {
il.sub();
System.out.println(il.value);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
il.notifyAll();
}
};
t1.start();
t2.start();
}
}
}
这就是终端中出现的内容:
Exception in thread "Thread-2" 1
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at anObject$2.run(anObject.java:53)
2
3
4
5
6
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at anObject$1.run(anObject.java:45)
非常感谢您的帮助! 问候
【问题讨论】:
标签: java multithreading synchronization wait notify