how many threads to run in java?

前端 未结 9 605
时光取名叫无心
时光取名叫无心 2021-02-03 16:05

I had this brilliant idea to speed up the time needed for generating 36 files: use 36 threads!! Unfortunately if I start one connection (one j2ssh connection object

9条回答
  •  被撕碎了的回忆
    2021-02-03 16:49

    You could narrow it down to a more reasonable number of threads with an ExecutorService. You probably want to use something near the number of processor cores available, e.g:

    int threads = Runtime.getRuntime().availableProcessors();
    ExecutorService service = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < 36; i++) {
        service.execute(new Runnable() {
            public void run() {
                // do what you need per file here
            }
        });
    }
    service.shutdown();
    

提交回复
热议问题