I am trying to figure out what is wrong with this thread program in java. Can anyone shed some light? Here is the code:
public class Z {
private Account account = new Account();
private Thread[] thread = new Thread[100];
public static void main(String[] args) {
Z test = new Z();
System.out.println("What is balance ? " + test.account.getBalance());
}
public Z() {
ThreadGroup g = new ThreadGroup("group");
boolean done = false;
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
thread[i] = new Thread(g, new AddAPennyThread(), "t" + i);
thread[i].start();
System.out.println("depositor: " + thread[i].getName());
}
// Check if all the threads are finished
while (!done)
if (g.activeCount() == 0)
done = true;
}
// A thread for adding a penny to the account
class AddAPennyThread extends Thread {
public void run() {
account.deposit(1);
}
}
// An inner class for account
class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
int newBalance = balance + amount;
balance = newBalance;
}
}
}
It compiles and runs fine. It was a test question I missed and wnated to know what is actually wrong with it. Thanks!
There is not a single bit dedicated to synchronization of 100 threads all working on exactly one (1!!!) piece of data.
Anything can happen. “Anything” includes that the code as it is works most of the time due some “coincidences”:
System.out.println.This adds up to: This might work in most test-runs. But it is an incorrect and non-deterministic program.