rendegen
2009-12-22 23:26
浏览 255
已采纳

线程报错 大家看看啊

package jack;


public class ThreadA {

    private static Object lock = new Object();
    private static Object lock1 = new Object();

    public static void main(String[] args) {
        ThreadB threadB = new ThreadB(lock);
        
        threadB.start();

        System.out.println("threadB is Start.....");
        synchronized (lock1) {
            ThreadC threadC = new ThreadC(lock);
            threadC.start();

            /* try { */
            System.out.println("Waiting for b to complete...");

            /* threadB.wait(); */

            /*
             * } catch (InterruptedException e) { // TODO Auto-generated catch
             * block }
             */
            System.out.println("Total is :" + threadB.total);

        }

    }
}

class ThreadB extends Thread {

    Object object;
    ThreadB(Object object)
    {
        this.object=object;
    }
    int total = 0;

    public void run() {
        // TODO Auto-generated method stub
        synchronized (object) {
            System.out.println("ThreadB is running..");
            for (int i = 0; i < 100; i++) {
                total += i;
                System.out.println("total is " + total);

                if (i == 50) {
                    try {

                        this.wait();
                    } catch (InterruptedException e) {
                    }
                }
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                }
            }
        }

    }
}

class ThreadC extends Thread {
    Object obj = null;

    ThreadC(Object obj) {
        this.obj=obj;
    }

    int total = 0;

    public void run() {
        // TODO Auto-generated method stub
        synchronized (obj) {
            System.out.println("ThreadC is running..");
            for (int i = 0; i < 100; i++) {
                total += i;
                System.out.println("TOTAL_C is " + total);
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                }
            }
            notify();
        }

    }
}

 

 

报错内容:

java.lang.IllegalMonitorStateException: current thread not owner
 at java.lang.Object.wait(Native Method)
 at java.lang.Object.wait(Unknown Source)
 at rendegen.ThreadB.run(ThreadA.java:55)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • liuiyu220 2009-12-23 09:34
    已采纳

    55行:this.wait(); 改成object.wait();
    90行:notify(); 改成obj.notify();
    因为你加锁的对象是object而不是当前的thread。所以你要用object的wait()方法是具有该对象锁的线程等待。唤醒的时候同理

    点赞 打赏 评论

相关推荐 更多相似问题