java 併發synchronized使用

從版本1.0開始,java中每一個對象都有一個內部鎖,若是一個方法用synchronized修飾,那麼對象的鎖將保護整個方法,也就是說要調用該方法,線程必須得到內部的對象鎖java

換句話說dom

public synchronized void method(){

  method body

}

等價於this

public void method(){

this.lock();
try{
method body;
}
finally{this.unlock}


}

 

內部對象只有一個相關條件,wait方法添加一個線程到等待集中,notifyAll方法解除等待線程的阻塞狀態spa

package reentrant_lock;

/**
 * Created by luozhitao on 2017/8/23.
 */
public class bank_syn {

    private double [] accounts;

    public bank_syn(int n,double bance){

        accounts=new double[n];

        for(int i=0;i<n;i++){

            accounts[i]=bance;


        }



    }
//


    public synchronized  void tansfer(int from,int to,double transf_num) throws InterruptedException{

        while (accounts[from]<transf_num)
            wait();


        accounts[from]-=transf_num;
        System.out.printf("轉出帳戶轉出%f 剩餘 %10.2f",transf_num,accounts[from]);

        accounts[to]+=transf_num;
        System.out.printf("轉入帳戶目前餘額爲 %10.2f",accounts[to]);


        notifyAll();
        System.out.printf(" 目前全部帳戶總額爲 %10.2f",get_total());


    }


    public synchronized double get_total(){

        double sum=0;

        for (double d:accounts){


            sum+=d;
        }

        return sum;
    }


    //
    public int size(){


        return accounts.length;
    }

}

 

主線程線程

package reentrant_lock;

/**
 * Created by luozhitao on 2017/8/18.
 */
public class transferRunnable implements Runnable {

 //   private Bank bank;
    private bank_syn bank;
    private int fromAccount;
    private double maxAccount;
    private int DELAY=10;
    int flag=0;


    public transferRunnable(bank_syn b,int from,double max){
        this.bank=b;
        this.fromAccount=from;
        this.maxAccount=max;

    }




    public void run() {


        try{
            while (true){
                int toAccount=(int)((bank.size()-1)*Math.random());

                System.out.println("toAccount ="+toAccount);
                double account_m=maxAccount*Math.random();
                System.out.println("account_m is "+account_m);
                bank.tansfer(fromAccount,toAccount,account_m);

                Thread.sleep((int) (DELAY * Math.random()));
                flag++;


            }
        }catch (InterruptedException e){e.printStackTrace();}

    }
}

maincode

package reentrant_lock;

/**
 * Created by luozhitao on 2017/8/23.
 */
public class bank_testsyn {


    private static int accoun_num=100;
    private static double init_num=1000;

    public static void main(String [] args){


        bank_syn syn=new bank_syn(accoun_num,init_num);



        for(int i=0;i<accoun_num;i++){
            transferRunnable transferrun = new transferRunnable(syn,i,init_num);
            Thread t=new Thread(transferrun);
            t.start();

        }



    }

}
相關文章
相關標籤/搜索