作者: geffon 時間: 2018-12-29 18:15 標題: Java 食唔盡個CPU ?
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class Runner {
- public static void main(String[] args) {
- ExecutorService newCachedThreadPool= Executors.newCachedThreadPool();
- //ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(500);
- ArrayList<String> testlist;
- File file = new File("C:\\test.txt");
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new FileReader(file));
- String tempString = null;
- Integer line = 0;
- testlist= new ArrayList<String>();
- while ((tempString = reader.readLine()) != null) {
- portlist.add(tempString);
- line++;
- }
- reader.close();
- System.out.println(testlist.size());
- for(int i=0;i<testlist.size();i++){
- final String tmpString = testlist.get(i);
- newCachedThreadPool.execute(new Runnable() {
- @Override
- public void run() {
- try {
- TestProgram a = new TestProgram();
- a.start(tmpString);
- } catch (InterruptedException e) {
- System.out.println("exception");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- }
- }
- }
似乎好似剩係用左單核咁樣樣,code 中 test.txt 為600行,即New 左TestProgram Class六百個同時執行,都係冇乜CPU使用率
作者: vichui 時間: 2018-12-29 18:25
你個TestProgram 行咩先?
行唔行得盡睇你Coding 食幾多resource..
無論用newFixedThreadPool 定 newCachedThreadPool,CPU使用率都係幾%,點解決?
似乎好似剩係用左單核咁樣 ...
geffon 發表於 2018-12-29 18:15
作者: geffon 時間: 2018-12-29 18:33
行HTTPClient 大量 GET POST
同時行600—1000個
newFixedThreadPool 無論教幾多 都係卡下卡下
newCachedThreadPool 都卡下卡下
作者: rabbit82047 時間: 2018-12-29 19:55
http get/post 大部份時間係等資料
作者: vichui 時間: 2018-12-29 20:42
咁呢個係network唔夠快,唔關CPU事, network 可以係自己, 可以係Internet...
作者: masseffect 時間: 2018-12-29 20:58
重點係,成個PROGRAM係IO INTENSIVE,所以根本唔會用到好快嘅CPU
就算你個NETWORK 快到好似HDD,甚至SSD咁快,一樣唔會用到好多CPU
作者: java2 時間: 2018-12-30 01:26
一睇你catch io exception 就知唔係 cpu intensive process, 食得幾多cpu

你想食cpu 咪寫d cpu intensive process, 例如做挖礦果d sha256 hash運算囉
無論用newFixedThreadPool 定 newCachedThreadPool,CPU使用率都係幾%,點解決?
似乎好似剩係用左單核咁樣 ...
geffon 發表於 2018-12-29 18:15
作者: yanjar 時間: 2018-12-30 21:28
我都寫過類似 program, 但network通常係bottleneck (用屋企個100Mb/s)
其實java multithreading係用得盡 CPU 的
作者: YuiNarusawa 時間: 2018-12-30 22:13
Java用thread pool開600條thread 真係玩自己, 建議用Java NIO或Node.js呢d event driven既方法
作者: hihihi123hk 時間: 2018-12-31 11:54
行HTTPClient 大量 GET POST
同時行600—1000個
newFixedThreadPool 無論教幾多 都係卡下卡下
n ...
geffon 發表於 2018-12-29 18:33
自己開 VisualVM 睇啦
用JVM 其中一大原因係因為 Debugging tool 發展得好
via HKEPC IR Pro 3.4.0 - iOS(2.3.3)
作者: rmhc 時間: 2019-1-1 00:21
提示: 作者被禁止或刪除 內容自動屏蔽
作者: ffchung 時間: 2019-1-28 10:05
你 TestProgram 裡面行緊 synchronized function ? 如果係,行幾多thread 都係要排隊.

