多线程环境下的线程不安全问题(2)

多线程环境下的线程不安全问题(2)
解决上条笔记所提到的线程不安全问题.

线程安全可以通过使用synchronizaed关键字的方法………

具体解释:

使用 synchronized 关键字后,方法就被 同步监视器所锁定,由于多条线程在这里使用的是同一个对象,所以就存在了线程的锁定问题

,一个线程的开始必须等待其它线程结束之后,从而保证数据和线程的安全。

补充:

观察java源代码,会发现 Vector,StringBuffer 等线程安全的类都采用了  synchronized 关键字来修饰。

改动Account类:

public class Account {

     private Integer balance;

     public Account(Integer balance) {
           super();
           this. balance = balance;
     }

     public synchronized Integer getBalance() {
           return balance;
     }

     public void setBalance(Integer balance) {
           this. balance = balance;
     }
     
     public synchronized void draw(Integer drawAccount){
           if( balance>= drawAccount){
               System. out.println(Thread. currentThread().getName()+"取钱成功,吐出钞票:" +drawAccount );
               balance-= drawAccount;
              System. out.println( "余额为:"+balance );
          } else{
               System. out.println(Thread. currentThread().getName()+"余额不足,取钱失败!" );
          }
     }
}

运行结果:





posted @ 2015-05-26 20:31  外禅内定,程序人生  阅读(219)  评论(0编辑  收藏  举报