title: Java get CPU usage percentage of cores
body: <p>I want to get total CPU usage of all cores. I need to print something like this: </p>
  
  <pre><code>Cpu 1: 33%
  Cpu 2: 12%
  Cpu 3: 66%
  Cpu 4: 100%
  </code></pre>
  
  <p>I tried to use this code: </p>
  
  <pre><code>OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
  RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
  int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
  long prevUpTime = runtimeMXBean.getUptime();
  long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
  double cpuUsage;
  try
  {
      Thread.sleep(500);
  }
  catch (Exception ignored) { }
  
  operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
  long upTime = runtimeMXBean.getUptime();
  long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
  long elapsedCpu = processCpuTime - prevProcessCpuTime;
  long elapsedTime = upTime - prevUpTime;
  
  cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
  System.out.println("Java CPU: " + cpuUsage);
  </code></pre>
  
  <p>But this code gives me output like this: <code>Java CPU: 27.504911422729492</code>.
  Can someone help me with this?</p>