5 回答
TA贡献1860条经验 获得超9个赞
实际上线程中不应该有else,把else注释掉就正确了。 如果加上else后,该线程会在wait后不再notify,导致另一个线程无限wait。
public class Test {
public static Object object = new Object();
public static boolean printA = true;
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
threadA.start();
ThreadB threadB = new ThreadB();
threadB.start();
}
}
class ThreadA extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
synchronized (Test.object) {
if(!Test.printA) {
try {
Test.object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}/* else {*/
System.out.println("A");
Test.printA = false;
Test.object.notify();
/*}*/
}
}
}
}
class ThreadB extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
synchronized (Test.object) {
if(Test.printA) {
try {
Test.object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}/* else { */
System.out.println("B");
Test.printA = true;
Test.object.notify();
/*}*/
}
}
}
}
TA贡献1829条经验 获得超7个赞
TA贡献1719条经验 获得超6个赞
TA贡献1884条经验 获得超4个赞
很明显ThreadB先wait,但代码却ThreadA先调用.... 只要让ThreadB先执行就可以了
ThreadB threadB = new ThreadB();
threadB.start();
Thread.sleep(10);
ThreadA threadA = new ThreadA();
threadA.start();
注意:两个Thread同时执行,java并不能能保证先调用的Thread先执行。
添加回答
举报