我可以通过不可变对象使这个类线程安全吗?

时间:2016-02-20 05:41:39

标签: java multithreading

我有一个班级,其中我有2个人检查余额并从普通帐户中提取资金..我通过synchronized关键字使交易线程安全但是它有很多开销,我有阅读他们提供的不可变对象和线程安全性。但我无法通过不可变对象

使这个类线程安全

代码:

final class bank implements Runnable
{
private final int balance,min_balance;

bank(int bal,int mbal)
{
  this.balance=bal;
  this.min_balance=mbal;
}
@Override
public void run()
{
   transaction();

}
public void transaction()
{
   if(checkBalance()> min_balance)
    {
     System.out.println("checkin is done by : "+Thread.currentThread().getName()
             +" and Balance left in the account is : "+checkBalance()); 
     System.out.println(Thread.currentThread().getName()+" is going to sleep ...");
    try{

       Thread.currentThread().sleep(2000); }
       catch(Exception e){
       }
    System.out.println(Thread.currentThread().getName()+" Woke up ..");
    withdraw();  
    System.out.println(Thread.currentThread().getName()+" has made the withdrawl ..");
   }
   else{
      lowBalance();   
   }
}

int checkBalance()
{
   return balance;
 }
 void lowBalance()
 {
     System.out.println("balance is not adequate");
 }

void withdraw()
{
   balance=balance-20;  //this wont work as balance is private
}

}

public class ryanmonica {

  public static void main(String args[])
  {
   bank obj=new bank(100,20);
   Thread t1=new Thread(obj);
   Thread t2=new Thread(obj);
   t1.setName("Ryan");
   t2.setName("Monica");
   t1.start();
   t2.start(); 

 }
}

1 个答案:

答案 0 :(得分:1)

不可变对象的状态永远不会改变。由于您的实例需要更改状态($data = 'grant_type=client_credentials'; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); balance正在更改),因此您需要使用同步机制。

不可变对象是线程安全的,因为它们不允许在其实例中进行状态更改。

相关问题