我想弄清楚这个线程程序在java中有什么问题。任何人都可以解释一下吗?这是代码:
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;
}
}
}
它编译并运行良好。这是一个我错过的测试问题,我想知道它到底有什么问题。谢谢!