求大神解析一下下面这个代码为什么

DS623089578 2017-06-14 05:33:51
原本想要实现多生产---单消费的模式,消费线程在第一次执行通知生产线程增加值,在线程增加值并且通知消费者线程,然后结束循环!原因在于通知的消费者线程并没有做出响应, 结果发生死锁!当不使用break的时候程序正常执行!不知道这是什么原因!
package thread;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentContainer {
static AtomicReference<Integer> money = new AtomicReference<Integer>();
static ReentrantLock lock = new ReentrantLock();
static Condition c1 = lock.newCondition();
static Condition c2 = lock.newCondition();
public static void main(String[] args) {
money.set(30);
for (int i = 0; i < 30; i++) {
new Thread() {
public void run() {
while(true) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"进入等待"+this);
c1.await();
System.out.println(Thread.currentThread().getName()+"被唤醒");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Integer m = money.get();
if(money.compareAndSet(m, m+20)) {
System.out.println("余额小于20元,充值成功,余额:"+money.get()+"元");
c2.signal();
break;
}else {
System.out.println("修改失败");
}
lock.unlock();
}
};
}.start();
}
new Thread() {
public void run() {
while(true) {
System.out.println("--");
lock.lock();
Integer m = money.get();
if(money.compareAndSet(m, m - 20)) {
System.out.println("客户成功消费了20元,余额:"+money.get());
c1.signal();
try {
c2.await();
System.out.println("执行了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.unlock();
}
}
}.start();
}
}
...全文
236 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
elim168 2017-06-14
  • 打赏
  • 举报
回复
原因在于加上了break后就跳出了while循环,后面的lock.unlock()就执行不到了。锁一直被占用,而没有释放,所以就死锁了。

62,621

社区成员

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

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