2011-10-13 74 views
0

我有以下代碼。它拋出一個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(); 
     } 
    } 



} 
+0

嘗試發佈實際堆棧跟蹤。在詢問更多與線程有關的內容之前,你還應該在你之前的問題中檢查答案。 – Robin

回答

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

我真的不知道你是怎麼想它來執行,但你穿上線繩鎖定和調用wait()在「這',這是什麼導致你的例外。