【发布时间】:2015-06-22 17:15:37
【问题描述】:
我正在尝试为线程运行以下程序,并期望变量对象应该由两个不同的线程更新。很奇怪,它只是显示值“加法-1”和“乘法-2”。但是当我使用调试器并逐步调试它时,“加法”和乘法就会按预期发生。如果我将“Thread.sleep”放在“P”的“运行”方法中 1000 毫秒。它工作正常。我已经注释掉了'Thread.sleep'的代码,但是如果你取消注释并运行它,你会发现预期的结果。谁能给我解释一下?
public class TestingThreads {
public static void main(String[] args) {
Variable b = new Variable();
Thread tp = new Thread(new P(b));
Thread tq = new Thread(new Q(b));
tp.start();
tq.start();
try {
tp.join();
tq.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Variable {
int i = 0;
boolean on = true;
public synchronized void addition() {
if (!on) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i = i + 1;
on=false;
notify();
System.out.println("addition " + i);
}
public synchronized void multiply() {
if (on) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i = i * 2;
on=true;
notify();
System.out.println("multiply " + i);
}
}
class P implements Runnable {
Variable b;
P(Variable b) {
this.b = b;
}
@Override
public void run() {
while (true) {
/*uncomment it and it will work fine.*/
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
b.addition();
}
}
}
class Q implements Runnable {
Variable b;
Q(Variable b) {
this.b = b;
}
@Override
public void run() {
while (true) {
b.multiply();
}
}
}
【问题讨论】:
标签: java multithreading