62,623
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
}