Java并发编程实战(使用synchronized实现同步方法)(2)

/**
    * Main method of the example
    * @param args
    */
    public static void main(String[] args) {
        // Creates a new account ...
        Account    account=new Account();
        // an initialize its balance to 1000
        account.setBalance(1000);
       
        // Creates a new Company and a Thread to run its task
        Company    company=new Company(account);
        Thread companyThread=new Thread(company);
        // Creates a new Bank and a Thread to run its task
        Bank bank=new Bank(account);
        Thread bankThread=new Thread(bank);
       
        // Prints the initial balance
        System.out.printf("Account : Initial Balance: %f\n",account.getBalance());
       
        // Starts the Threads
        companyThread.start();
        bankThread.start();

try {
            // Wait for the finalization of the Threads
            companyThread.join();
            bankThread.join();
            // Print the final balance
            System.out.printf("Account : Final Balance: %f\n",account.getBalance());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

结果,相同时间内,存与取执行后应该是相等的。如果我们在方法中不去使用synchronized关键字,那么得出的结果就不对了。
  
  Account : Initial Balance: 1000.000000
  Account : Final Balance: 1000.000000

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c28373e828785c4ad907686d204c1936.html