ThreadLocal优化共享对象实例

本文通过对比多线程环境下共享Random实例与使用ThreadLocal封装Random实例的方式,展示了ThreadLocal带来的性能提升。实验结果显示,采用ThreadLocal可以显著提高随机数生成操作的效率。

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

ThreadLocal(性能优化)


import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class test2 {
// 每个线程要产生的随机数数量
public static final int get_count = 10000000;
// 参加工作的线程数量
public static final int thread_count = 4;
// 定义线程池
static ExecutorService exe = Executors.newFixedThreadPool(thread_count);
// 被多线程共享的Random实例用于产生随机数
public static Random rnd = new Random(123);
// ThreadLocal封装的Random
public static ThreadLocal<Random> tRnd = new ThreadLocal<Random>() {


@Override
protected Random initialValue() {


return new Random(123);
}


};


public static class RndTask implements Callable<Long> {


private int mode = 0;


public RndTask(int mode) {
super();
this.mode = mode;
}


public Random getRandom() {
if (mode == 0) {
return rnd;
} else if (mode == 1) {
return tRnd.get();
} else {
return null;
}
}


// 每个线程会产生若干随机数,完成后,记录消耗时间
@Override
public Long call() throws Exception {
long b = System.currentTimeMillis();
for (int i = 0; i < get_count; i++) {
getRandom().nextInt();
}
long e = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + "spend"
+ (e - b) + "ms");
return e - b;
}


}


public static void main(String[] args) throws InterruptedException,
ExecutionException {
Future<Long>[] futs = new Future[thread_count];
for (int i = 0; i < thread_count; i++) {
futs[i] = exe.submit(new RndTask(0));
}


long totaltime = 0;
for (int i = 0; i < thread_count; i++) {
totaltime += futs[i].get();
}


System.out.println("多线程访问同一个Random实例" + totaltime + "ms");


// 使用ThreadLocal的情况


for (int i = 0; i < thread_count; i++) {
futs[i] = exe.submit(new RndTask(1));
}
totaltime = 0;


for (int i = 0; i < thread_count; i++) {
totaltime += futs[i].get();
}


System.out.println("使用ThreadLocal包装Random实例" + totaltime + "ms");


exe.shutdown();
}
}




结果输出:
pool-1-thread-1spend1780ms
pool-1-thread-3spend1803ms
pool-1-thread-2spend2220ms
pool-1-thread-4spend2189ms
多线程访问同一个Random实例7992ms
pool-1-thread-3spend815ms
pool-1-thread-1spend851ms
pool-1-thread-4spend853ms
pool-1-thread-2spend855ms

使用ThreadLocal包装Random实例3374ms

我们发现使用ThreadLocal对Random进行封装.效率大大提高。



每天努力一点,每天都在进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

powerfuler

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值