多线程的程序帮忙看看

zhangbaokun 2007-12-17 08:50:56

package com.zbk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestThread
{

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
MutiLine mul = new MutiLine();
for (int i = 0; i < 10; i++)
{
Thread newThread = new Thread(mul);
newThread.start();
}
}

}

class MutiLine implements Runnable
{
Bank bank = new Bank(4, 10000);

public void run()
{
while (true)
{
try
{

int from = (int) (Math.random() * 4);
int to = (int) (Math.random() * 4);
double money = 10000 * Math.random();
bank.transfer(from, to, money);
Thread.sleep(1);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
System.out.println("a");
}
}
}
}

class Bank
{
private double[] group;
private ReentrantLock locker;
private Condition condition;

Bank(int num, double everySalary)
{
group = new double[num];
for (int i = 0; i < group.length; i++)
{
group[i] = everySalary;
}
locker = new ReentrantLock();
condition = locker.newCondition();
}

public void transfer(int from, int to, double money)
throws InterruptedException
{
locker.lock();
try
{
while (group[from] < money)
{
condition.await();
}
group[from] -= money;
group[to] += money;
System.out.print(Thread.currentThread().getName() + ": ");
System.out.println("from:" + from + " to:" + to + ": all money: "
+ computeAll());
condition.signalAll();

}
finally
{
locker.unlock();
}
}

public double computeAll()
{
locker.lock();
try
{
double total = 0;
for (int i = 0; i < group.length; i++)
{
total += group[i];
}
return total;
}
finally
{
locker.unlock();
}
}

}


我写的一个多线程之间关于锁和阻塞及解除阻塞的小程序
为什么运行一会程序就死掉了,是不是哪出死锁了还是怎么的,请大家帮我看一下
...全文
132 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ltc_mouse 2007-12-18
  • 打赏
  • 举报
回复
代码可能没有问题,这个随机转帐本身就会形成所有线程都等待的局面。
我测试了几次,发现经过一小段时间后,大部分的钱会转到某一个帐户,其他三个帐户资金较少了,但偏偏他们之间又期望进行大资金转帐,于是都在等天上掉馅饼....

其实,由于采用随机,只要进行了帐户间的不为0的转帐,就一定会出现某个帐号资金少于10000,有个很极端的例子:所有线程都要求这个少于10000的帐号转出10000的资金,结果都饿死了...
zhangbaokun 2007-12-18
  • 打赏
  • 举报
回复
ok了,我也实验出结果了,确实是这么回事
liusdream 2007-12-18
  • 打赏
  • 举报
回复
3楼分析的很正确,
修改一下你的打印输出,在转出金额不足时,打印一些数据.
不难发现最后所有的线程都从余额比较少的帐号转较多的钱,所有线程最后都在等待!
zhangbaokun 2007-12-17
  • 打赏
  • 举报
回复
好像不是那的问题,我在那加上condition.signalAll();
一样会死掉
ludahumsn 2007-12-17
  • 打赏
  • 举报
回复
public double computeAll()
{
locker.lock();
try
{
double total = 0;
for (int i = 0; i < group.length; i++)
{
total += group[i];
}
return total;
}
finally
{
locker.unlock();
}
}
没有唤醒其它线程

62,623

社区成员

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

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