繁体   English   中英

为什么这种形式的块同步比其他块快?

[英]Why is this form of block synchronizing faster than the other?

因此,我刚刚完成了有关同步的任务,并且对获得的结果感到好奇,因为我不太了解为什么一种形式比另一种形式更快。

有一个帐户类,定义如下:

public class Account {

    /*
     * ------------
     * Data members
     * ------------
     */

    /**
     * Attribute presents an account number
     */

    private int acc;
    /**
     * Attribute that presents an customer name
     */
    private String name;
    /**
     * Attribute that presents an account balance
     */
    private double balance;

    /*
     * ------------
     * Constructors
     * ------------
     */

    /**
     * Assigns account number, name and balance.
     *
     * @param acc A unique integer that represents account number
     * @param name A string indicating human-readable customer's name
     * @param balance A double indicating account balance
     */

    public Account(int acc, String name, double balance) {
        super();
        this.acc = acc;
        this.name = name;
        this.balance = balance;
    }


    @Override
    /**
     * equals method works as == operator 
     * it checks if two accounts are identical
     */
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Account other = (Account) obj;
        if (acc != other.acc)
            return false;
        if (Double.doubleToLongBits(balance) != Double
                .doubleToLongBits(other.balance))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (acc!=other.acc)return false;
        return true;
    }

    /**
     * Accessor for account no
     * @return account no
     */
    public int getAcc() {
        return acc;
    }

    /**
     * Mutator for account no 
     * @param acc A unique int for acoount number
     */
    public void setAcc(int acc) {
        this.acc = acc;
    }

    /**
     * Accessor for a customer's name
     * @return a customer's name
     */
    public String getName() {
        return name;
    }

    /**
     * Mutator for a customer name
     * @param name A string that represents a customer name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Accessor for account balance
     * @return an account balance
     */
    public double getBalance() {
        return balance;
    }

    /**
     * Mutator for account balance
     * @param balance A double that represents an account balance
     */
    public void setBalance(double balance) {
        this.balance = balance;
    }

    /**
     * A method to print this account 
     */
    public String toString(){
        return "Account: "+acc+" \tName: "+name+" \tBalance:\t"+balance;
    }

    /**
     * A method that allows a customer to deposit money into this account
     * @param amount A double that represents a deposit amount
     */
    public void debosit(double amount){

        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        double k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
            balance = balance + amount;
        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;

    }

    /**
     * A method that allows a customer to withdraw money from this account
     * @param amount A double that represents a withdrawal amount
     */
    public void withdraw(double amount){

        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements

        double k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
            balance = balance - amount;
        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
    }


}

public void debosit(double amount){

        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        double k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
            balance = balance + amount;
        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;

    }

    /**
     * A method that allows a customer to withdraw money from this account
     * @param amount A double that represents a withdrawal amount
     */
    public void withdraw(double amount){

        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements

        double k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
            balance = balance - amount;
        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
    }

存款人类如下所示:

public class Depositor extends Thread {
    private Account account ;
    public Depositor(Account account){
        this.account = account;
    }


    public void run(){
        synchronized(account){
        for (int i=0;i<10000000;i++)
        {
            account.debosit(10);
            }
        /*          
        try {
                sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
        }

    }

}

而且提款器类类似于存款,只是运行提款方法而不是存款一种。

具有main方法的类如下:

public class AccountManager {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Account [] account = new Account[10];
        Depositor [] deposit = new Depositor[10];
        Withdrawer [] withdraw = new Withdrawer[10];

        // The birth of  10 accounts
        account[0] = new Account(1234,"Mike",1000);
        account[1] = new Account(2345,"Adam",2000);
        account[2] = new Account(3456,"Linda",3000);
        account[3] = new Account(4567,"John",4000);
        account[4] = new Account(5678,"Rami",5000);
        account[5] = new Account(6789,"Lee",6000);
        account[6] = new Account(7890,"Tom",7000);
        account[7] = new Account(8901,"Lisa",8000);
        account[8] = new Account(9012,"Sam",9000);
        account[9] = new Account(4321,"Ted",10000);

        // The birth of 10 depositors 
        deposit[0] = new Depositor(account[0]);
        deposit[1] = new Depositor(account[1]);
        deposit[2] = new Depositor(account[2]);
        deposit[3] = new Depositor(account[3]);
        deposit[4] = new Depositor(account[4]);
        deposit[5] = new Depositor(account[5]);
        deposit[6] = new Depositor(account[6]);
        deposit[7] = new Depositor(account[7]);
        deposit[8] = new Depositor(account[8]);
        deposit[9] = new Depositor(account[9]);

        // The birth of  10 withdraws 
        withdraw[0] = new Withdrawer(account[0]);
        withdraw[1] = new Withdrawer(account[1]);
        withdraw[2] = new Withdrawer(account[2]);
        withdraw[3] = new Withdrawer(account[3]);
        withdraw[4] = new Withdrawer(account[4]);
        withdraw[5] = new Withdrawer(account[5]);
        withdraw[6] = new Withdrawer(account[6]);
        withdraw[7] = new Withdrawer(account[7]);
        withdraw[8] = new Withdrawer(account[8]);
        withdraw[9] = new Withdrawer(account[9]);

        System.out.println("Print initial account balances");
        // Print initial account balances
        for(int i=0;i<10;i++)
            System.out.println(account[i]);

        // Get start time in milliseconds 
        long start = System.currentTimeMillis(); 

        System.out.println("Depositor and Withdrawal threads have been created");
        /*
         * Interleave all threads
         */
        for(int i=0; i<10; i++){
            deposit[i].start();
            withdraw[i].start();
        }


        for(int i=0; i<10; i++){
            try {
                deposit[i].join();
                withdraw[i].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // Get elapsed time in milliseconds 
        long elapsedTimeMillis = System.currentTimeMillis()-start; 

        System.out.println("Print final account balances after all the child thread terminated...");
        // Print final account balances after all the child thread terminated...    
        for(int i=0;i<10;i++)
            System.out.println(account[i]);
        // Get elapsed time in seconds 
        float elapsedTimeSec = elapsedTimeMillis/1000F;

        System.out.println("Elapsed time in milliseconds "+elapsedTimeMillis);
        System.out.println("Elapsed time in seconds is "+elapsedTimeSec);

        //  Get elapsed time in minutes 
        float elapsedTimeMin = elapsedTimeMillis/(60*1000F); 
        // Get elapsed time in hours 
        float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F); 
        // Get elapsed time in days 
        float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F); 

    }

}

抱歉,有很多代码,但是最后我的问题是:

如果使用块同步,则可以将其直接放在帐户类中,如下所示:

public void withdraw(double amount){

        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements

        double k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
            synchronized(this)
                balance = balance - amount;
        // Waste some time doing fake computations
        // do not remove or modify any of the following 3 statements
        k = 999999999;
        for(int i=0;i<100;i++)
            k = k / 2;
    }

两种解决方案都完成后,总共需要1秒钟才能运行。 但是,如果将同步转移到提款机和存款人类,则看起来像这样:

public void run(){

        // Withdraw 10 CAD into instance variable account
        for (int i=0;i<10000000;i++)
        {
            synchronized(account)
                account.withdraw(10);

        }
    }

这大约需要运行时间的1/10。

为什么是这样? 他们不应该花相同的时间吗?

锁定有开销。 如果锁定次数增加了100倍,则锁定开销应增加100倍。

之所以看不到100倍的差异,而只有10倍的原因,是因为代码在做其他事情,但是如果您只有锁定,您会注意到更大的差异。 除非JIT编译器会注意到循环中的同步块并将其吊起,否则似乎在测试中没有这样做。

如果同步块位于withdraw()方法上,则一次只能有一个线程执行该方法,这意味着当一个线程正在执行“伪计算”时,其他线程必须等待。 看起来像这样:

获取锁->伪造计算器->修改余额->伪造计算器->释放锁

但是,如果仅同步更改方法中的一行,而1个线程拥有锁,则其他线程可以执行“伪计算”,这样可以节省一些时间。 看起来像这样

假计算器->获取锁->修改余额->释放锁->假计算器

注意,在第二种同步方式中,线程可以在另一个线程修改余额并释放锁之后立即获取锁,因此它不必等待伪计算。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM