多线程与单线程的效率对比

在计算比较简单,任务耗时较少的情况下,Java使用多线程执行任务的效率往往没有单线程高,
因为多线程在执行期间切换线程上下文的频率会成倍提高,执行简单任务时多线程的线程切换耗时会大量增加执行时间,所以多线程并发最好是尽量用在耗时较多或IO请求的程序上

package hsy.com;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    private static ExecutorService executorService = Executors.newFixedThreadPool(10);
    public static void main(String[] args){
        long stTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 100000; j++) {
                System.out.println(j);
            }
        }
        System.out.println(System.currentTimeMillis()-stTime);
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<Object> list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        stTime = System.currentTimeMillis();
        CompletableFuture[] objects = list.stream().map(i -> CompletableFuture.runAsync(() -> {
            for (int j = 0; j < 100000; j++) {
                System.out.println(j);
            }
        }, executorService)).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(objects).join();
        System.out.println(System.currentTimeMillis()-stTime);

    }
}


执行结果

单线程 2800ms
多线程 3400ms

上一篇:CompletableFuture异步编排


下一篇:异步调用