Java Multi-threaded bank withdrawals

Source: Internet
Author: User

  1. Package Net.okren.java;
  2. Import java.io.*;
  3. Account
  4. Class account{
  5. private Float balance = 1000;
  6. Public Float getbalance () {
  7. return balance;
  8. }
  9. public void setbalance (float balance) {
  10. this.balance = balance;
  11. }
  12. public synchronized Void withdraw (float money) {
  13. if (balance >= money) {
  14. System.out.println ("Take away" + Money +"cash");
  15. try{
  16. Thread.Sleep (1000);
  17. }catch (Interruptedexception e) {
  18. E.printstacktrace ();
  19. }
  20. Balance-= money;
  21. }else{
  22. SYSTEM.OUT.PRINTLN ("Insufficient balance");
  23. }
  24. }
  25. }
  26. Class TestAccount1 extends thread{
  27. private account Account;
  28. Public TestAccount1 (account account) {
  29. this.account = account;
  30. }
  31. public Void Run () {
  32. Account.withdraw (800);
  33. System.out.println ("balance is" + account.getbalance ());
  34. }
  35. }
  36. Class TestAccount2 extends thread{
  37. private account Account;
  38. Public TestAccount2 (account account) {
  39. this.account = account;
  40. }
  41. public Void Run () {
  42. Account.withdraw (700);
  43. System.out.println ("balance is" + account.getbalance ());
  44. }
  45. }
  46. Public class Javatest {
  47. public static void Main (string[] args) {
  48. Account Account = new account ();
  49. TestAccount1 T1 = new TestAccount1 (account);
  50. TestAccount2 t2 = new TestAccount2 (account);
  51. T1.start ();
  52. T2.start ();
  53. }
  54. }

Java Multi-threaded bank withdrawals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.