ReentrantLock and Synchronized (from peter)

本文通过模拟高并发场景,对比了使用显式锁ReentrantLock和内置同步机制的性能差异。实验结果显示,ReentrantLock提供了更高的操作吞吐量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class HighContentionSimulator implements Runnable {
enum Mode implements Runnable {
LOCK {
private final Lock lock = new ReentrantLock();
public void run() {
lock.lock();
try {
operation();
} finally {
lock.unlock();
}
}},
SYNC {
public synchronized void run() {
operation();
}}
}

private final Mode mode;
private final int count;

public HighContentionSimulator(Mode mode, int count) {
this.mode = mode;
this.count = count;
}

public void run() {
for (int i = 0; i < count; i++)
mode.run();
}

public static void operation() {
Double d = Math.random();
}

private static void test(Mode mode) throws InterruptedException {
int threadNumber = 4;
int count = 1000 * 1000;
long start = System.nanoTime();
Thread[] threads = new Thread[threadNumber];
for (int i = 0; i < threadNumber; i++)
(threads[i] = new Thread(new HighContentionSimulator(mode, count))).start();
for (int i = 0; i < threadNumber; i++)
threads[i].join();
long rate = 1000L * 1000 * 1000 * count * threadNumber / (System.nanoTime() - start);
System.out.printf("%s operations/second %,d%n", mode.toString(), rate);
}

public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 3; i++) {
test(Mode.LOCK);
test(Mode.SYNC);
}
}
}


Prints

LOCK operations/second 2,722,306
SYNC operations/second 967,460
LOCK operations/second 2,838,865
SYNC operations/second 972,421
LOCK operations/second 2,848,031
SYNC operations/second 1,094,899
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值