2017-07-21 132 views
0

我想學習多線程的基本概念。PingPong程序Java多線程

爲什麼我的乒乓程序只打印Ping 0 & Pong0,爲什麼notify()不啓動處於等待狀態的Ping線程?

公共類PingPong實現Runnable { String string;

public PingPong(String word) { 
    this.word = word; 
    } 

    public void run() { 

    synchronized (this) { 
     for (int i = 0; i < 10; i++) { 
     System.out.println(word + i); 
     try { 
      wait(); 
      notifyAll(); 
     } catch (Exception e) { 
      System.out.println(e.getMessage()); 
     } 
     } 
    } 
    } 

    public static void main(String[] args) { 

    Runnable p1 = new PingPong("ping"); 
    Thread t1 = new Thread(p1); 
    t1.start(); 

    Runnable p2 = new PingPong("pong"); 
    Thread t2 = new Thread(p2); 
    t2.start(); 

    } 

} 

輸出

ping0 
pong0 

我試圖消除wait()和它的印刷乒乓球,直到循環結束。但是這保證它會按順序打印?

爲什麼wait()跟在notify()不要求ping1線程開始執行?

回答

1
  1. 如果看到jstack,可以看到線程0和線程1正在等待不同的鎖。這是因爲你的p1和p2是不同的對象,所以當你使用synchronized (this)時,他們不會爭奪相同的鎖定,所以這種通知不起作用。嘗試使用另一個對象作爲鎖。
  2. 等待通知後需要運行。當兩個線程進入等待狀態時,其他線程都不能通知它們。

試試這個代碼:

String word; 
Object a; 
public PingPong(String word, Object a) { 
    this.word = word; 
    this.a = a; 
} 

public void run() { 

    synchronized (a) { 
     for (int i = 0; i < 10; i++) { 
      System.out.println(word + i); 
      try { 

       a.notifyAll(); 
       a.wait(); 
      } catch (Exception e) { 
       System.out.println(e.getMessage()); 
      } 
     } 
    } 
} 

public static void main(String[] args) throws InterruptedException { 

    Object a = new Object(); 
    Runnable p1 = new PingPong("ping", a); 
    Thread t1 = new Thread(p1); 
    t1.start(); 

    Runnable p2 = new PingPong("pong", a); 
    Thread t2 = new Thread(p2); 
    t2.start(); 

}