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();
}
}}
我写的一个多线程之间关于锁和阻塞及解除阻塞的小程序
为什么运行一会程序就死掉了,是不是哪出死锁了还是怎么的,请大家帮我看一下

解决方案 »

  1.   

    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();
            }
        }
    没有唤醒其它线程
      

  2.   

    好像不是那的问题,我在那加上condition.signalAll();
    一样会死掉