2017-07-21 144 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(); 

}