2014年4月30日星期三

Java_014:WAITING线程例子 (摘录+整理)

1.  WaitThread.java

public class WaitThread implements Runnable{
public void run() {
        synchronized(this) {
                try {
                                this.wait();
                      } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                      }
        }
   }
   public static void main(String[] args) {
        WaitThread t1 = new WaitThread();
        Thread ta = new Thread(t1, "A");
        Thread tb = new Thread(t1, "B");
        ta.start();
        tb.start();
   }

}

2. 线程A和线程B的thread dump
(1)线程A的状态是in Object.wait():WAITING (on object monitor)。
(2)线程B的状态也是in Object.wait():WAITING (on object monitor)。

"B" prio=5 tid=0x00007fc16d83d000 nid=0x5903 in Object.wait() [0x00000001215cb000]
   java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc80> (a WaitThread)
at java.lang.Object.wait(Object.java:503)
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc80> (a WaitThread)
at java.lang.Thread.run(Thread.java:744)

"A" prio=5 tid=0x00007fc16d83c000 nid=0x5703 in Object.wait() [0x00000001214c8000]
   java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc80> (a WaitThread)
at java.lang.Object.wait(Object.java:503)
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc80> (a WaitThread)
at java.lang.Thread.run(Thread.java:744)

原因解释:
线程A获取Monitor后:locked <0x00000007aab2bc80>,又调用wait(),释放了锁:waiting on <0x00000007aab2bc80>。
因为线程A释放了锁<0x00000007aab2bc80>,线程B得以获取该锁,然后线程B也调用wait(),释放了该锁。
现在,线程A和线程B都在等待其它线程调用锁对象的notify()或notifyall()方法,将它们再次“唤醒”。

没有评论: