So, I’m having a hard time trying to resolve a college problem…
What I need to do is :
I need to create an app that simulates money transfer between accounts using concurrency.
I need to create a method which does this transference in a Bank class like this:
transfer(int from, int to, int value)
Then I need to create a TransferThread class which manages this transferences.
Problem is I’m getting deadlocks all the time…
What I’ve done so far:
TransferThread:
public void run() {
int para,de,valor;
try
{
while(!interrupted())
{
para = new Random().nextInt(banco.getNUMCONTAS());
de = new Random().nextInt(banco.getNUMCONTAS());
valor = (int) (10000 * Math.random());
if(de == para)
continue;
banco.transfer(de, para, valor);
sleep(1);
}
}catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
Banco:
public synchronized void transfer(int de, int para, int valor) {
while(contas[de].getSaldo() - valor <= 0)
{
try
{
wait();
}catch(InterruptedException e)
{
}
}
notifyAll();
contas[de].setSaldo(-valor);
contas[para].setSaldo(valor);
System.out.println("Conta num: " + contas[de].getNum() + ". Saldo: " + contas[de].getSaldo());
System.out.println("Conta num: " + contas[para].getNum() + ". Saldo: " + contas[para].getSaldo());
}
And main:
Banco b = new Banco();
TransferThread[] threads = new TransferThread[2];
for(int i = 0; i < 2; i++){
threads[i] = new TransferThread(b);
threads[i].start();
}
How can I make this work?
Although banking example is very often used when introducing threading to students, the regular ideas it aims to teach are not the issue in your code.
For some reason you seem to be waiting forever when there isn’t enough money in the account, and well, it’s not going to magically appear there if both threads wait! They are both simply stuck in infinite loop.