ThreadLocal优化共享对象实例

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 tRnd = new ThreadLocal() {


@Override
protected Random initialValue() {


return new Random(123);
}


};


public static class RndTask implements Callable {


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[] 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进行封装.效率大大提高。



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

你可能感兴趣的:(高并发,ThreadLocal)