-
Thread questions
I have these 3 classes --
Code:
public class Account {
private int balance = 0;
void deposit(int amount)
{
balance += amount;
}
synchronized int getBalance()
{
return balance;
}
}
Code:
public class Customer extends Thread{
Account account;
Customer(Account account)
{
this.account = account;
}
public void run()
{
try {
for(int i = 0;i<100000;i++)
{
account.deposit(10);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Code:
public class BankDemo {
public final static int NUMCUSTOMERS = 10;
public static void main(String args[])
{
Account account = new Account();
Customer customers[] = new Customer[NUMCUSTOMERS];
for(int i=0;i<NUMCUSTOMERS;i++)
{
customers[i] = new Customer(account);
customers[i].start();
}
//Wait for customer threads to complete
for(int i = 0;i<NUMCUSTOMERS;i++)
{
try {
customers[i].join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(account.getBalance());
}
}
Basically, it just makes some customers (as threads) and calls the deposit method a lot. One question I have is that before I put the synchronized modifier in the deposit method, my output was wrong (it is supposed to be 10,000,000 and it came out to some random crazy number). Why does the program not work without the synchronized modifier? Also, in the BankDemo, why do I have to call the join() method to end a thread?
-
Reason not work without the synchronized modifier(Thread Interference (The Java™ Tutorials > Essential Classes > Concurrency))
j.join() method...
Thread object j is currently executing, causes the current thread to pause execution until t's thread terminates
(Joins (The Java™ Tutorials > Essential Classes > Concurrency))
i have a question
all Customer use the same account?
-
Hi,
Look into this below link to know more about synchronized modifier.
Sun Certified Java Programmer Pre-Exam Essentials