一个关于使用String做锁的问题(PS:不要使用string做锁)
来源:互联网 发布:彭雪茹 知乎 编辑:程序博客网 时间:2024/05/19 05:31
今天写一段程序,里面有一个锁的嵌套,在里面,我wait释放了一个锁,另一个锁并没有释放,但是在运行的时候,没有释放的锁竟然能够获得。
package Thread.test;/** * @author Administrator */public class NotifyTestString {public static class Thread1 implements Runnable {public String lock;public String lockAfter;public Thread1(String lock, String lockAfter) {this.lock = lock;this.lockAfter = lockAfter;}public void run() {synchronized (lock) {synchronized (lockAfter) {while (true) {lockAfter.notify();System.out.println(" lockAfter notified! ");try {System.out.println("try to wait!");lock.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("the end of synchronized code locked by lockAfter!");}}}}}public static void main(String[] args) throws InterruptedException {String lockAfter = "";String lock = "";Thread1 t1 = new Thread1(lock, lockAfter);new Thread(t1).start();Thread.currentThread().sleep(100);synchronized (lockAfter) {System.out.println("gain the lock");}}}
这段代码会打印出gain the lock,这就奇怪了,我释放的是lock锁,并没有释放lockAfter锁啊,为什么主线程还能获得lockAfter锁呢?
难道wait把两个锁全部释放了?这不可能啊!jdk中明明写的非常清楚
Note that the <tt>wait</tt> method, as it places the current thread
* into the wait set for this object, unlocks only this object; any
* other objects on which the current thread may be synchronized remain
* locked while the thread waits.
瞅了一下,晕,最初级的一个错误,自己的两个String是同一个对象,因为如果是直接将字符串赋给一个String变量的话,jvm会首先在字符串池中看看有没有,没有的话,就创建一个字符串,放进字符串池中,然后返回引用,如果有的话,就返回池中的这个,我这样声明的两个字符串其实是一个,就是说,两次获得的锁其实是一个,这就是为什么锁获得到的原因,
0 0
- 一个关于使用String做锁的问题(PS:不要使用string做锁)
- hash_map 使用 string做 key
- 做一个string类的扩展方法
- scramble string (使用动态规划和递归做)
- 关于std::string的使用问题
- 正确使用String类的几点注意 (转载 只做学习之用)
- 用string和char做不同输入判断时候的代码(作为输入判断使用)
- 一个关于String问题
- 关于String.TrimEnd的使用
- 关于使用SHFileOperation做文件操作的问题
- 关于使用QQ做第三方登录的问题!
- C++中string做函数传递参数的危险问题
- aix使用g++编译时一个stl string的问题
- 使用string.Format需要注意的一个性能问题
- 使用string.Format需要注意的一个性能问题
- 在使用JdbcTemplate.queryForMap(String )的时候发现一个问题.
- 关于音频播放使用setDataSource(String path)遇到的问题
- 关于PS做文字的一些总结
- 继承extends
- SQL查询基本结构
- 物理全明星梦之队
- 阅读优秀代码是提高开发人员修为的一种捷径
- js(复选框,全选,全部选,反选教程)
- 一个关于使用String做锁的问题(PS:不要使用string做锁)
- JVM中方法区
- Tomcat原理
- 客户端TortoiseSVN的安装及使用方法
- Jar mismatch! Fix your dependencies
- 智能手环产品分析(资料来源网上,自己总结)
- Java中的byte
- ActionScript关键词
- local0-local7 in syslog