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

在不考虑多线程的情况下,很多类代码都是完全正确的,但是如果放在多线程环境下,这些代码就很容易出错,我们称这些类为 线程不安全类 。多线 程环境下使用线程安全类 才是安全的。

下面是一个线程不安全类的例子:

public class Account {
      private Integer balance ;

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

      public Integer getBalance() {
           return balance ;
     }

      public void setBalance(Integer balance ) {
           this . balance = balance ;
     }
     
      public 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()+ "余额不足,取钱失败!" );
          }
     }
}



public class DrawThread extends Thread{
      private Account account ;
      private Integer drawAccount ;
      public DrawThread(String name ,Account account , Integer drawAccount ) {
           super ( name );
           this . account = account ;
           this . drawAccount = drawAccount ;
     }
      //当多条线程共享一个数据的时候,会涉及到线程安全问题
      public void run(){
           account .draw( drawAccount );
     }
}

public class Main{
      public static void main(String[] args ) {
          Account account = new Account(1000);
           //模拟两条线程对于同一个账户取钱
           new DrawThread( "甲" , account , 800).start();;
           new DrawThread( "乙" , account , 800).start();;
     }
}

运行结果:

262035120911063.png
很明显线程同步时发生了问题,线程不安全。

那么如何解决呢?下一节讲。






转载于:https://www.cnblogs.com/ZhangJinkun/p/4531692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值