关于多线程同步的初步教程--使用synchronized

2014-11-23 23:19:12 · 作者: · 浏览: 0
在编写一个类时,如果该类中的代码可能运行于多线程环境下,那么就要考虑同步的问题。在Java中内置了语言级的同步原语--synchronized,这也大大简化了Java中多线程同步的使用。我们首先编写一个非常简单的多线程的程序,是模拟银行中的多个线程同时对同一个储蓄账户进行存款、取款操作的。
在程序中我们使用了一个简化版本的Account类,代表了一个银行账户的信息。在主程序中我们首先生成了1000个线程,然后启动它们,每一个线程都对John的账户进行存100元,然后马上又取出100元。这样,对于John的账户来说,最终账户的余额应该是还是1000元才对。然而运行的结果却超出我们的想像,首先来看看我们的演示代码:

  1. class Account {
  2. String name;
  3. float amount;
  4. public Account(String name, float amount) {
  5. this.name = name;
  6. this.amount = amount;
  7. }
  8. public void deposit(float amt) {
  9. float tmp = amount;
  10. tmp += amt;
  11. try {
  12. Thread.sleep(100);//模拟其它处理所需要的时间,比如刷新数据库
  13. } catch (InterruptedException e) {
  14. // ignore
  15. }
  16. amount = tmp;
  17. }
  18. public void withdraw(float amt) {
  19. float tmp = amount;
  20. tmp -= amt;
  21. try {
  22. Thread.sleep(100);//模拟其它处理所需要的时间,比如刷新数据库
  23. } catch (InterruptedException e) {
  24. // ignore
  25. }
  26. amount = tmp;
  27. }
  28. public float getBalance() {
  29. return amount;
  30. }
  31. }
  32. public class AccountTest{
  33. private static int NUM_OF_THREAD = 1000;
  34. static Thread[] threads = new Thread[NUM_OF_THREAD];
  35. public static void main(String[] args){
  36. final Account acc = new Account("John", 1000.0f);
  37. for (int i = 0; i< NUM_OF_THREAD; i++) {
  38. threads[i] = new Thread(new Runnable() {
  39. public void run() {
  40. acc.deposit(100.0f);
  41. acc.withdraw(100.0f);
  42. }
  43. });
  44. threads[i].start();
  45. }
  46. for (int i=0; i
  47. try {
  48. threads[i