package com.chong;
public class Main {
public static void main(String args[]){
Object obj=new Object();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1 end");
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
synchronized (obj) {
obj.notify();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 end");
}
}
});
t1.start();
t2.start();
}
}
如上代码,结果是:t2先执行完,t1后执行完。
查资料,notify()方法是通知一个等待在该对象上的线程,不会释放锁。
那么,obj.notify()方法,写在同步代码块里的最开始或者最末尾处,jvm内部处理逻辑上有什么差异吗?平时写代码,在这里有什么需要注意的点吗?
4 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
你这么写只是个演示代码,wait()和notify()是配合生产者-消费者模型使用的。Android中的Volley框架也是使用这种原理来进行多线程的并发调度。
不需要考虑JVM,你只需要考虑释放时机和通知时间,建议参考我的这篇博客:Java并发写作——wait-notify机制
一只甜甜圈
TA贡献1836条经验 获得超5个赞
引用jdk6中wait方法的注释
The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to thenotifymethod or thenotifyAllmethod.
对应到题主的代码wait调用后会释放obj对象的锁。
另外,sleep和yield方法是不会释放对象锁的。
添加回答
举报
0/150
提交
取消
