• 4.3.3 thread对性能有何帮助


    public class ThreadLocalDemo {
    public static final int GE_COUNT = 10000000;
    public static final int THREAD_COUT = 4;

    static ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUT);
    public static Random random = new Random(123);

    public static ThreadLocal<Random> randomThreadLocal = new ThreadLocal<Random>() {
    protected Random initialValue() {
    return new Random(123);
    }
    };


    public static class RandomTask implements Callable<Long> {

    private int mode = 0;

    public RandomTask(int mode) {
    this.mode = mode;
    }

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


    public Long call() throws Exception {
    long b = System.currentTimeMillis();

    for (int i = 0; i < GE_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 ExecutionException, InterruptedException {
    Future<Long>[] futures = new Future[THREAD_COUT];
    for (int i = 0; i < THREAD_COUT; i++) {
    futures[i] = executorService.submit(new RandomTask(0));
    }

    long totalTime = 0;

    for (int i = 0; i < THREAD_COUT; i++) {
    totalTime += futures[i].get();
    }
    System.out.println("多线程访问同一个Random实例:" + totalTime + "ms");
    executorService.shutdown();
    executorService=Executors.newFixedThreadPool(4);
    //ThreadLocal的情况
    for (int i = 0; i < THREAD_COUT; i++) {
    futures[i] = executorService.submit(new RandomTask(1));
    }
    totalTime = 0;
    for (int i = 0; i < THREAD_COUT; i++) {
    totalTime += futures[i].get();
    }
    executorService.shutdown();
    System.out.println("使用ThreadLocal包装Random实例:" + totalTime + "ms");

    }


    运行结果:

    pool-1-thread-3 spend1353ms
    pool-1-thread-1 spend1542ms
    pool-1-thread-2 spend1573ms
    pool-1-thread-4 spend1593ms
    多线程访问同一个Random实例:6061ms
    pool-2-thread-1 spend531ms
    pool-2-thread-2 spend512ms
    pool-2-thread-3 spend450ms
    pool-2-thread-4 spend414ms
    使用ThreadLocal包装Random实例:1907ms




  • 相关阅读:
    支持向量机(Support Vector Machine / SVM)
    k-近邻算法(KNN)
    STM32端口模式配置——上拉、下拉、模拟、浮空输入;推挽、开漏、复用输出
    Catia V5-6R2017破解版|Catia V5-6R2017下载|安装破解步骤
    在远方
    快递 10 年,逆袭为王
    “四通一达”本一家,这家人是如何“承包”中国快递半壁江山的?
    JavaScript中的内存释放
    常见的几种JavaScript内存泄露
    span(行级元素)在不定高的div(块级元素)中垂直居中的方法
  • 原文地址:https://www.cnblogs.com/anxbb/p/8651524.html
Copyright © 2020-2023  润新知