在线程中解决IllegalMonitorException?

时间:2011-10-13 16:54:58

标签: 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();
        }   
    }   



}

2 个答案:

答案 0 :(得分: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)。

答案 1 :(得分:0)

我很抱歉有点迟到的回复,但你可以试试这个

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 ThreadSample implements Runnable {
String name = "vimal";
static int id = 0;

public void run() {
    System.out.println("Runnable " + this.name);
    // setNAme("Manish");
    synchronized (this) {
        System.out.println(this.name);
        this.name = "Manish " + this.id;
        this.id++;
        try {
            wait();
            System.out
                    .println("Thread " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            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) {
        e.printStackTrace();
    }
}
}

我真的不知道你希望它如何执行,但是你在对String进行锁定并在'this'上调用wait(),这就是导致异常的原因。