2012-12-16 55 views
-1

我想弄清楚这个线程程序在java中出了什么问题。任何人都可以点亮一下吗?这里是代码:这个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; 
     } 
    } 
} 

它编译和运行良好。这是我错过的一个测试问题,想知道它究竟有什么问题。谢谢!

+2

它应该做什么?它不是做什么的? –

回答

4

没有专门用于同步100个线程的单个比特,所有线程都完全在之间工作,一个(1 !!!)数据片段。

任何东西都可能发生。 “任何事情”都包括代码,因为它大部分时间都是由于某些“巧合”而发挥作用的:

  • 手头的任务非常小。 (仅限添加)
  • 任务已创建并立即启动。
  • 两个“create + start”对之间有一个小延迟:System.out.println

这就增加了:这威力工作试运行。但这是一个不正确和不确定的程序。

+0

你是在说“比赛状况?” – Clint

+0

@Clint:是的。确实。 –

+0

谢谢!你已经被检查过! – Clint

0
[Tread1] int newBalance = balance + amount; 
[Tread2] int newBalance = balance + amount; 
[Tread1] balance = newBalance; 
[Tread2] balance = newBalance; 

public synchronized void deposit(int amount) 
0

balance应该是一个private volatile int(这样的Java知道永远不会缓存它 - 它的价值是负责不同的线程之间切换访问没有一个线程知道),并Account#deposit(int amount)一个public synchronized void(使Java使得该方法身体的关键区域,并防止任何它接触的对象同时访问,确保值的完整性balance)。

此外,自己实例化100个线程与new介绍了很多的开销 - 尽管我明白这只是一个玩具例子,一个更有效的方式来做到这一点是使用Java thread pool