在线程中解决IllegalMonitorException?

Vim*_*deo 0 java synchronization

我有以下代码.它给我一个java.lang.IllegalMonitorStateException.为什么这样,我该如何解决这个问题?

public class Threads  {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //Thread Th = new Threads();
        Thread th = new Thread (new thread1 ());
        th.start();
        Thread th1 = new Thread (new thread1 ());
        th1.start();
    }
}



class thread1 implements Runnable{
    String name = "vimal";
    static int id = 0;
    public void run() {
        System.out.println("Runnable "+this.name);
        //setNAme("Manish");
        synchronized(name){
            System.out.println(this.name);
            this.name = "Manish "+this.id;
            this.id++;
            try {
                wait(1000);System.out.println("Thread "+Thread.currentThread().getName());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    }

    public synchronized void setNAme(String name){
        try {
            System.out.println("Thread "+Thread.currentThread().getName());
            wait(1000);
            this.name = name;
            System.out.println("Name "+this.name);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }   



}
Run Code Online (Sandbox Code Playgroud)

aav*_*aav 5

你正在调用wait(1000)而不在run()方法中对'this'对象持有监视器.检查Object.wait()的javadoc:

http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#wait()

如果你只想延迟1秒 - 你应该使用Thread.sleep(1000).