java同步机制性能比较小测试

来源:互联网 发布:淘宝权重值 编辑:程序博客网 时间:2024/04/29 19:16

测试结果:

47 ms - thread unsafe

3869 ms - synchronized method

3911 ms - synchronized (lock)

3986 ms - synchronized (this)

2319 ms - ReentrantLock

import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class Account {private int balance;private Lock lock = new ReentrantLock();public Account(int balance) {this.balance = balance;}public int getBalance() {return balance;}public void add(int num) {lock.lock();try {balance = balance + num;} finally {lock.unlock();}}public void withdraw(int num) {lock.lock();try {balance = balance - num;} finally {lock.unlock();}}public static void main(String[] args) throws InterruptedException {long startTime = System.currentTimeMillis();Account account = new Account(10000);Thread a = new Thread(new AddThread(account, 100));Thread b = new Thread(new WithdrawThread(account, 100));a.start();b.start();a.join();b.join();System.out.println(account.getBalance());System.out.println("elapsed time:"+ (System.currentTimeMillis() - startTime));}static class AddThread implements Runnable {Account account;int amount;public AddThread(Account account, int amount) {this.account = account;this.amount = amount;}public void run() {for (int i = 0; i < 10000000; i++) {account.add(amount);}}}static class WithdrawThread implements Runnable {Account account;int amount;public WithdrawThread(Account account, int amount) {this.account = account;this.amount = amount;}public void run() {for (int i = 0; i < 10000000; i++) {account.withdraw(amount);}}}}


0 0