Решить IllegalMonitorException в потоке? - PullRequest
0 голосов
/ 13 октября 2011

У меня есть следующие коды.Это вызывает у меня исключение 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 ]

5 голосов
/ 13 октября 2011

вы вызываете wait (1000) без удержания монитора объекта this в методе run (). проверьте javadoc для Object.wait ():

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

Если вы просто хотите задержку в 1 с - вы должны использовать Thread.sleep (1000).

0 голосов
/ 07 апреля 2016

Прошу прощения за небольшой поздний ответ, но вы можете попробовать это

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 и вызывали wait () поверх«это», вот что вызывает у вас исключение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...