Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Semaphore problem

Status
Not open for further replies.

Scooby316

IS-IT--Management
Jan 30, 2003
32
0
0
US
Hi all, Having a problem with this code. It should run 2 threads but at the moment it is only running first void run. I am a noob so any help is much apprecated. Cheers in advance.


import Semaphore.Semaphore ;

public class TestAccounts {
private Object lock = new Object ();

Semaphore sema = new Semaphore (1);
Accounts accts;

public static void main(String[] args) {
// create a TestAccounts object
TestAccounts test = new TestAccounts();
}

public TestAccounts () {
accts = new Accounts ();

int noOfAccounts = 3;//accts.length;

/*
Create and start a thread to add the balances of
the accounts contained in the Accounts object referenced by accts.
*/
AddAccounts addThread = new AddAccounts(accts);


/*
o Create and start a thread to transfer 100 from acct2
to acct1 in the Accounts object referenced by accts (
i.e. the accounts at locations 2 and 1 in the array
holding the accounts).
*/
TransferFunds transFund = new TransferFunds(2,1,100,accts);

addThread.start();
transFund.start();
}
// inner class
public class AddAccounts extends Thread {
Accounts acctsAA;

public AddAccounts(Accounts a) {
acctsAA = a;
}

public void run () {

synchronized (lock) {
int total = acctsAA.addAccounts();
System.out.println ("ADD: total =" + total);

sema.semaSignal();
lock.notifyAll();
}
}
}
// inner class
public class TransferFunds extends Thread {
int from, to, amount;
Accounts acctsTF;

public TransferFunds(int fromAcct, int toAcct, int i, Accounts a) {
from = fromAcct;
to = toAcct;
amount = i;
acctsTF = a;
}

public void run () {

try{
synchronized (lock) {

while (false);
lock.wait();

acctsTF.transfer (from, to, amount);
sema.semaWait();

}
}catch (InterruptedException e) {}


}
}
}
 
you should post the content of Accounts and Semaphore.Semaphore
for us to trace.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top