Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. package example;
  2.  
  3. public class Account {
  4. private double balance;
  5.  
  6. public Account(double balance) {
  7. super();
  8. this.balance = balance;
  9. }
  10.  
  11. public synchronized void deposit(double amount) {
  12. balance += amount;
  13. }
  14.  
  15. public double getBalance() {
  16. return balance;
  17. }
  18. }
  19.  
  20. package example;
  21.  
  22. public class AccountTester extends Thread {
  23. private Account account;
  24. private double amount;
  25.  
  26. public AccountTester(Account account, double amount) {
  27. this.account = account;
  28. this.amount = amount;
  29. }
  30.  
  31. public static void main(String[] args) {
  32. Account account = new Account(0);
  33. AccountTester tester1 = new AccountTester(account, 1.0);
  34. AccountTester tester2 = new AccountTester(account, 2.0);
  35. tester1.start();
  36. tester2.start();
  37. // Why do I need the main thread to join threads
  38. // tester1 and tester2 for synchronized to work?
  39. try {
  40. tester1.join();
  41. tester2.join();
  42. } catch (InterruptedException e) {
  43. System.err.println(e);
  44. }
  45. System.out.println("End balance: " + account.getBalance());
  46. }
  47.  
  48. @Override
  49. public void run() {
  50. for (int i = 0; i < 1000; i++) {
  51. account.deposit(amount);
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement