我有以下代碼。它拋出一個java.lang.IllegalMonitorStateException異常。爲什麼是這樣的,我該如何解決這個問題?在線程中解決IllegalMonitorException?
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();
}
}
}
嘗試發佈實際堆棧跟蹤。在詢問更多與線程有關的內容之前,你還應該在你之前的問題中檢查答案。 – Robin