1. WaitThread.java
public class WaitThread implements Runnable{
2. 线程A和线程B的thread dump
(1)线程A的状态是in Object.wait():TIMED_WAITING (on object monitor)。
(2)线程B的状态也是in Object.wait():TIMED_WAITING (on object monitor)。
"B" prio=5 tid=0x00007fc52c8bf000 nid=0x5903 in Object.wait() [0x000000011af67000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at java.lang.Thread.run(Thread.java:744)
"A" prio=5 tid=0x00007fc52c039000 nid=0x5703 in Object.wait() [0x000000011ae64000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at java.lang.Thread.run(Thread.java:744)
原因解释:
与上一个例子代码基本相同,只是在wait()方法上增加了一个时间参数,因此具体状态由WAITING 变为TIMED_WAITING,即等待一定的时间。
如果在这段时间内,其它线程调用锁对象的notify()或notifyall()方法,则再次试图获取该对象的锁。
当过了指定时间后,也会再次试图获取该对象的锁。
线程A获取Monitor后:locked <0x00000007aab2bc80>,又调用wait(),释放了锁:waiting on <0x00000007aab2bc80>。0x00000007aab2bc80>0x00000007aab2bc80>
因为线程A释放了锁<0x00000007aab2bc80>,线程B得以获取该锁,然后线程B也调用wait(),释放了该锁。0x00000007aab2bc80>
public class WaitThread implements Runnable{
public void run() {
synchronized(this) {
try {
this.wait(200000L);
} 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();
}
}
(1)线程A的状态是in Object.wait():TIMED_WAITING (on object monitor)。
(2)线程B的状态也是in Object.wait():TIMED_WAITING (on object monitor)。
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at java.lang.Thread.run(Thread.java:744)
"A" prio=5 tid=0x00007fc52c039000 nid=0x5703 in Object.wait() [0x000000011ae64000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at WaitThread.run(WaitThread.java:5)
- locked <0x00000007aab2bc98> (a WaitThread)0x00000007aab2bc98>
at java.lang.Thread.run(Thread.java:744)
原因解释:
与上一个例子代码基本相同,只是在wait()方法上增加了一个时间参数,因此具体状态由WAITING 变为TIMED_WAITING,即等待一定的时间。
如果在这段时间内,其它线程调用锁对象的notify()或notifyall()方法,则再次试图获取该对象的锁。
当过了指定时间后,也会再次试图获取该对象的锁。
线程A获取Monitor后:locked <0x00000007aab2bc80>,又调用wait(),释放了锁:waiting on <0x00000007aab2bc80>。0x00000007aab2bc80>0x00000007aab2bc80>
因为线程A释放了锁<0x00000007aab2bc80>,线程B得以获取该锁,然后线程B也调用wait(),释放了该锁。0x00000007aab2bc80>
没有评论:
发表评论