java的wait 吊起线程的时候 会不会释放synchronized锁呢

careercup163 2013-03-08 07:45:36
java的wait 吊起线程的时候 会不会释放synchronized锁呢?

我现在做的其实算是一个 资源池的程序
public class Ziyuan<R> {

private Hashtable<R, Boolean> tab = new Hashtable<R, Boolean>();

public void add(R r) {
synchronized (tab) {
tab.put(r, false);
}
}

//使用这个资源
public void use(R r) {
synchronized (tab) {
if (tab.containsKey(r)) {
tab.put(r, true);
tab.notifyAll();
}
}
}

//停止使用资源
public void release(R r) {
synchronized (tab) {
if (tab.containsKey(r)) {
tab.put(r, false);
tab.notifyAll();
}
}
}

//关闭系统 需要等待所有资源停止使用
public void close() throws InterruptedException {
synchronized (tab) {
while (true) {
boolean able = true;
for (R r : tab.keySet()) {
if (tab.get(r)) {
able = false;
break;
}
}
if (!able) {
tab.wait(10000);
} else {
System.out.println("可以关闭了!");
break;
}
}
}
}
}


每次给名为tab的更改哈希表表数据时候 都会用synchronized锁上(布尔Boolean表示是否在使用),每次操作都会notify其他线程
close的时候 要判断是否所有tab的资源R都为false, 如果有一个资源在使用(有一个为true) 就tab.wait() 等待notify 但是我就是想知道跑 这个wait和notify 和 synchronized 会不会不兼容.....

请问大家如何设计这个问题
...全文
2293 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
bryant_5327 2015-08-28
  • 打赏
  • 举报
回复
谢谢楼主题这个问题,我也在迷惑这一点,培训老师没讲到。
hippoppower 2013-07-26
  • 打赏
  • 举报
回复
wait就是要在synchronized中用 不会不兼容
zzcdyx_ok 2013-07-25
  • 打赏
  • 举报
回复
wait()会立刻释放sycronized(obj)中的obj锁,以便其他线程可以执行obj.nodify() 但是nodify()不会立刻立刻释放sycronized(obj)中的obj锁,必须要等nodify()所在线程执行完sycronized(obj)块中的所有代码才会释放这把锁
nj_dobetter 2013-03-12
  • 打赏
  • 举报
回复
会释放 wait()的意思就是放弃已经持有的锁然后等待
北京-星辰 2013-03-10
  • 打赏
  • 举报
回复
会的,会让出锁的。
yanxing2012 2013-03-10
  • 打赏
  • 举报
回复
wait()会释放锁,yield(),sleep()不会放弃锁
zj304292653 2013-03-09
  • 打赏
  • 举报
回复
会释放,sleep不会释放
careercup163 2013-03-08
  • 打赏
  • 举报
回复
是作业。。。。。。所以不能用类库
rockets311 2013-03-08
  • 打赏
  • 举报
回复
java的wait吊起线程的时候释放synchronized锁。 看java.lang.Object的wait方法的API: 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 the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
龙四 2013-03-08
  • 打赏
  • 举报
回复
楼主说下想做什么功能,说不定类库中已经有了。 更多专业的并发内容,见这里:http://ifeve.com/ wait-notify见这里:http://www.ticmy.com/?p=219
龙四 2013-03-08
  • 打赏
  • 举报
回复
wait进入阻塞,就会释放当前锁,不然notify的时候也要持有同一把锁,它怎么获取得到

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧