CAS实战

import java.util.ArrayList;
import java.util.List;

public interface Account {
    
    
    Integer getBalance();

    void withdraw(Integer amount);

    static void demo(Account acount) {
    
    
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
    
    
            ts.add(new Thread(() -> {
    
    
                acount.withdraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
    
    
            try {
    
    
                t.join();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(acount.getBalance());
        System.out.println(String.format("花費時間為%s毫秒",(end-start)/1000_000));
    }
}

public class AccountSafeSyn implements Account {
    
    
    private Integer balance;

    public AccountSafeSyn() {
    
    
    }

    public AccountSafeSyn(Integer balance) {
    
    
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
    
    
        return this.balance;
    }

    @Override
    public void withdraw(Integer amount) {
    
    
        synchronized (this) {
    
    
            this.balance -= amount;
        }
    }
}
import java.util.concurrent.atomic.AtomicInteger;

public class AccountSafeCas implements Account {
    
    
    private AtomicInteger balance;

    public AccountSafeCas() {
    
    
    }

    public AccountSafeCas(Integer balance) {
    
    
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
    
    
        return this.balance.get();
    }

    @Override
    public void withdraw(Integer amount) {
    
    
        while(true) {
    
    
            int prev = balance.get();
            int next = prev - amount;
            // 這裏的關鍵是 CAS 是原子操作,由CPU锁住总线
            // 运算前如果balance等于prev,则将balance替换为next;否则不做操作
            if (balance.compareAndSet(prev,next)) {
    
    
                break;
            }
        }
    }
}
public class MainClass {
    
    
    public static void main(String[] args) {
    
    
        Account account = new AccountSafeSyn(10000);
        Account.demo(account);

        Account account2 = new AccountSafeCas(10000);
        Account.demo(account2);
    }
}

使用synchronize关键字
0
花費時間為250毫秒

使用cas关键字
0
花費時間為182毫秒

总结
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41948178/article/details/109566583
Cas
今日推荐