2016-10-30 6 views
0

일부 정보가 들어있는 텍스트 파일을로드하고 해당 정보를 기반으로 여러 스레드를 실행하는 프로그램이 있습니다. 각 스레드는 하나의 프로세스입니다. 여기에 내 코드입니다 : 내가 runMultiClient 클래스에서 그 변수에 도달 할 수있는 방법이 있나요프로세스 CPU 사용량 얻기

OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class); 
      cpuLoad = osBean.getProcessCpuLoad(); 

: 내 Client.jar 파일 내부

public class runMultiClient { 
public static void main(String[] args){ 
    List<Process> PRlist = new ArrayList<Process>(); 
    List<String[]> commandsList = new ArrayList<String[]>(); 
    boolean running = true; 

    if (args.length == 2 && args[0].matches("-f")){ 
     String dir = System.getProperty("user.dir"); 
     String path = dir + "/" + args[1]; 
     FileReader fr; 
     try { 
      fr = new FileReader(path); 
      BufferedReader bf = new BufferedReader(fr); 

      String line = ""; 
      while ((line = bf.readLine()) != null){ 
       String[] tk = line.split(" "); 
       String[] cmd = {"java", "-jar", "Client.jar", "-a", tk[0], "-p", tk[1], 
         "-u", tk[2], "-pw", tk[3], "-m", tk[4], "-s", tk[5]}; 
       Process pr = new ProcessBuilder().inheritIO().command(cmd).start(); 
       PRlist.add(pr); 
       commandsList.add(cmd); 
       System.out.println(tk[4] + " streaming process is established."); 
      } 
     } 
     catch (FileNotFoundException ex) {ex.printStackTrace();} 
     catch (IOException ex) {ex.printStackTrace();} 
    } else { 
     System.out.println("No stream file was specified."); 
    } 
}} 

, 그 클래스의 CPU 부하를 모니터링하는 변수가 ? 그렇지 않은 경우 실행중인 프로세스에서 OperatingSystemMXBean을 사용하는 방법이 있습니까? 나는 pr.getClass()을 시도했지만, 아무데도 없어. 도움이 될 것입니다.

+0

당신이 완전한 클래스를 제공 할 수 있습니다를 어디에 cpuLoad 변수 위치 ? – developer

+0

할 수는 있겠지만 어떻게 도와 줄 수 있습니까? –

+0

'cpuLoad'는 다른 클래스의 공용 변수입니다. –

답변

2

옵션 # 1 : HTTP를 통해 JMX를 에이전트 라이브러리를 추가하고 노출

당신은 (다른 비슷한 일이 SimpleJMX입니다 그것은 HTTP/JSON을 통해 JMX 콩을 노출 그래서 이것은 상호 작용 작동하여 모니터링 응용 프로그램과 함께 Jolokia 에이전트를 묶을 수

. JMX 다른 언어 파이썬 같은 (와 같은 명령에서 문제를 해결할 때 매우 편안하게) 당신은 아파치 HTTP 클라이언트 등을 통해 관심의 MBean에 액세스 할 수 있습니다 그 후

옵션 # 2 :. JMX 클라이언트

원격 수 있습니다. 다음 매개 변수를 추가하여 연결 w

-Dcom.sun.management.jmxremote.port=9999 \ 
-Dcom.sun.management.jmxremote.authenticate=false \ 
-Dcom.sun.management.jmxremote.ssl=false 

그런 다음 당신은 다른 요구 사항에 대한 ProcessBuilder().inheritIO()를 호출해야하는 경우 확실하지 the tutorial

+0

원격 위치에서 모니터 할 필요가 없습니다. 'Client'를 위해 계산 된 값에 접근하기 위해서는'runMultiClient' 클래스가 필요합니다. –

+0

@DanyLavrov 원격 단어는 호출자가 MBean과 동일한 VM에 상주하지 않는다는 사실을 강조 표시 한 것입니다. 런처 프로세스는이 경우 TCP 소켓을 통해 실행 응용 프로그램과 통신합니다. – Ivan

+1

@DanyLavrov 동일한 프로세스에 있지 않으면 원격입니다. 자바는 일반적으로 공유 메모리를 사용하지 않는다. –

1

에서처럼, jconsole을하고 손으로 쓴 JMX 클라이언트 코드에 의해 MBean에 액세스 할 수 있어야합니다 : 당신의 모니터링 응용 프로그램 시작 암탉 , 그렇지 않다면 System.out에 cpu로드를 주기적으로 기록하는 Client.jar 프로세스에서 데몬 스레드를 시작할 수 있습니다. 그런 다음 runMultiClient 스레드 [s]는 프로세스의 System.out을 나타내는 InputStream에서 스레드를 읽을 수 있습니다. 또는 스레드가 명령을 받아들이고 이에 따라 인쇄하도록하십시오. 거친 예 : 양산에서 client.jar에

실행이 다음 runMultiClient에

public static void startCmdListener() { 
    try { 
     Thread t = new Thread("CmdListener") { 
      BufferedReader br = null; 
      InputStreamReader isr = null; 
      final OperatingSystemMXBean os = (OperatingSystemMXBean) ManagementFactoryHelper.getOperatingSystemMXBean(); 
      public void run() { 
       try { 
        isr = new InputStreamReader(System.in); 
        br = new BufferedReader(isr); 
       } catch (Exception ex) { 
        ex.printStackTrace(System.err); 
        return; 
       } 
       try { 
        String cmd = null; 
        while(true) { 
         cmd = br.readLine(); 
         if("cpu".equalsIgnoreCase(cmd)) { // cpu command, print the process load 
          System.out.println(os.getProcessCpuLoad()); 
         } else if("exit".equalsIgnoreCase(cmd)) { // exit command, break 
          break; 
         } 
        } 
       } catch (Exception ex) { 
        ex.printStackTrace(System.err); 
        return; 
       } 

      } 
     }; 
     t.setDaemon(true); 
     t.start(); 
    } catch (Exception ex) { 
     ex.printStackTrace(System.err); 
    } 
} 

실행이 CPU 부하 얻을 :

public static double getCpu(OutputStream processIn, InputStream processOut) { 
    PrintStream ps = null; 
    BufferedReader br = null; 
    InputStreamReader isr = null; 

    try { 
     ps = new PrintStream(processIn); 
     isr = new InputStreamReader(processOut); 
     br = new BufferedReader(isr); 
     ps.println("cpu"); 
     ps.flush();   
     return Double.parseDouble(br.readLine()); 
    } catch (Exception ex) { 
     throw new RuntimeException(ex); 
    } finally { 
     if(ps!=null) try { ps.close(); } catch (Exception x) {} 
     if(br!=null) try { br.close(); } catch (Exception x) {} 
     if(isr!=null) try { isr.close(); } catch (Exception x) {} 
    } 
} 
+0

좋은 소리가 들립니다. 나는 그것을 시도 할 것이라고 생각한다. 고맙습니다 –