java吧 关注:1,249,838贴子:12,732,114
  • 4回复贴,共1

线程方面的不算太理解 寻求高手解答一下 谢谢

取消只看楼主收藏回复

public class Calculator extends Thread {
int total;
publicvoid run() {
synchronized (this) {
for (int i = 0; i < 101; i++) {
total += i;
}
}
notifyAll();
}
}
public class ReaderResult extends Thread {
Calculator c;
public ReaderResult(Calculator c) {
this.c = c;
}
public void run() {
synchronized (c) {
try {
System.out.println(Thread.currentThread() + "等待计算结果。。。");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "计算结果为:" + c.total);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
new ReaderResult(calculator).start();
new ReaderResult(calculator).start();
new ReaderResult(calculator).start();
calculator.start();
}
}
运行结果:
Thread[Thread-1,5,main]等待计算结果。。。
Thread[Thread-2,5,main]等待计算结果。。。
Thread[Thread-3,5,main]等待计算结果。。。
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.notifyAll(Native Method)
at threadtest.Calculator.run(Calculator.java:18)
Thread[Thread-1,5,main]计算结果为:5050
Thread[Thread-2,5,main]计算结果为:5050
Thread[Thread-3,5,main]计算结果为:5050
我不明白那个异常是什么意思 怎么出现的异常


1楼2012-06-07 19:13回复
    IllegalMonitorStateException
    抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。
    表示不理解这个异常是什么意思


    2楼2012-06-07 19:15
    回复
      没有人 ? 求解答


      3楼2012-06-07 20:11
      回复
        来个人就是水一下也行啊 我只是网页还是自己玩单机那?


        4楼2012-06-07 20:41
        回复
          额 谢谢帮我纠正的输入错误 不过 我就是不明白那个异常是怎么出现的 再有API里的那个异常的解释我也不理解是什么意思


          7楼2012-06-07 20:49
          回复