...
"Thread-0" #11 prio=5 os_prio=0 tid=0x0000000020bf7000 nid=0x4f94 waiting on condition [0x000000002189f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at Test$Thread1.run(Test.java:13)
Locked ownable synchronizers:
- None
...
"main" #1 prio=5 os_prio=0 tid=0x0000000004f63800 nid=0x431c in Object.wait() [0x0000000004eef000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076b6e0898> (a Test$Thread1)
at java.lang.Thread.join(Unknown Source)
- locked <0x000000076b6e0898> (a Test$Thread1)
at java.lang.Thread.join(Unknown Source)
at Test.main(Test.java:5)
Locked ownable synchronizers:
- None
...
下面演示wait方法导致的等待状态:
publicclassTest {publicstaticint i =0;publicstaticvoidmain(String[] args) throwsException {Thread1 t =newThread1();t.start();synchronized (t) {System.out.println("等待子线程");t.wait(); }System.out.println("主线程结束"); }staticclassThread1extendsThread { @Overridepublicvoidrun() {synchronized (this) {for (int i =0; i <10; i++) {try {System.out.println(i);Thread.sleep(1000); } catch (InterruptedException e) { } }notify(); } } }}
通过线程堆栈观察,主线程同样处于等待WAITING状态:
...
"main" #1 prio=5 os_prio=0 tid=0x0000000005983800 nid=0xb54 in Object.wait() [0x00000000058df000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076b6e0aa8> (a Test$Thread1)
at java.lang.Object.wait(Unknown Source)
at Test.main(Test.java:8)
- locked <0x000000076b6e0aa8> (a Test$Thread1)
Locked ownable synchronizers:
- None
...