【发布时间】:2015-04-01 18:25:31
【问题描述】:
我正在实现逻辑来理解等待和通知工作我发现了一些我无法分析的东西,当我用线程扩展类然后等待和通知按预期工作但是当我实现可运行接口时输出会有所不同
public class AdderThread extends Thread {
int total;
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 1000; i++) {
total += i;
}
notify();
}
}
public class WaitNotify {
public static void main(String[] args) {
AdderThread addrTh = new AdderThread();
addrTh.start();
// -1243309312
System.out.println("Total without Wait() " + addrTh.total);
}
}
当实现 Runnable 给我正确的答案时,意味着它正在等待线程完成任务,但是当我使用扩展线程时,它给我的答案为 0,即它没有等待线程完成任务。
public class WaitNotify {
public static void main(String[] args) {
AdderThread addrTh = new AdderThread();
addrTh.start();
// -1243309312
System.out.println("Total Before Wait " + addrTh.total);
synchronized (addrTh) {
try {
System.out.println("Waiting for Sum...");
addrTh.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Total " + addrTh.total);
}
}
}
【问题讨论】:
-
一开始你写的扩展是工作的,可运行的不是。最后,您说的是可运行的作品,而不是可扩展的作品。你读过你输入的内容吗?
-
对不起...我的意思是说,当我扩展线程时,如果没有 wait(),我的结果无法正确运行,因为线程仍在运行。但是,当我实现 Runnable 时,我的结果正在运行正确不使用 wait()
标签: java multithreading