2014-12-03 129 views
2

如何更改優先級的進程

List<String> commands = Arrays.asList(commandv); 
    ProcessBuilder pb = new ProcessBuilder("[C:\ffmpeg\ffmpeg.exe, -i, "C:\file\video.mp4",-flags, +loop, -cmp, +chroma, -partitions, +parti4x4+partp8x8+partb8x8, -me_method, umh, -subq, 6, -me_range, 16, -g, 250, -keyint_min, 25, -sc_threshold, 40, -i_qfactor, 0.71, -b_strategy, 1, -threads, 4, -b:v, 200k, , -r, 25, -v, warning, -ac, 1, -ab, 96k, -y, -vf, "scale=640:360", "C:\newVideo\video.mp4"]"); 
    Process proc = pb.start(); 

我怎樣才能從「HIGHT」在java中設置進程的優先級爲「低」?

回答

3

無法在Java中設置進程的優先級。
只有線程優先。
但是你可以使用系統命令與指定的優先級運行過程:
Linux的:new ProcessBuilder("nice", "-n", "10", "somecommand", "arg1", "arg2");
的Windows:new ProcessBuilder("cmd", "/C start /B /belownormal /WAIT javaws -sdasd");

0

這是與平臺相關的,我實現了這個針對Windows:

首先需要手柄然後使用JNI來改變進程的優先級:

package com.example.util; 

import java.lang.reflect.Field; 

public class ProcessUtil { 

    static { 
     try { 
      System.loadLibrary("ProcessUtil"); 
     } 
     catch (Throwable th) { 
      // do nothing 
     } 
    } 

    public static void changePrioToLow(Process process) { 
     String name = process.getClass().getName(); 
     if (!"java.lang.ProcessImpl".equals(name)) { 
      return; 
     } 
     try { 
      Field f = process.getClass().getDeclaredField("handle"); 
      f.setAccessible(true); 
      long handle = f.getLong(process); 
      f.setAccessible(false); 
      changePrioToLow(handle); 
     } 
     catch (Exception e) { 
      // do nothing 
     } 
    } 

    private static native void changePrioToLow(long handle); 
} 

相應的JNI頭ER(文件com_example_util_ProcessUtil.h)

#include <jni.h> 

#ifndef _Included_com_example_util_ProcessUtil 
#define _Included_com_example_util_ProcessUtil 
#ifdef __cplusplus 
extern "C" { 
#endif 

JNIEXPORT void JNICALL Java_com_example_util_ProcessUtil_changePrioToLow 
    (JNIEnv *, jclass, jlong); 

#ifdef __cplusplus 
} 
#endif 
#endif 

的JNI接口(文件com_example_util_ProcessUtil.cpp)

#include <jni.h> 
#define _WIN32_WINNT 0x0501 
#include <windows.h> 
#include "com_example_util_ProcessUtil.h" 

JNIEXPORT void JNICALL Java_com_example_util_ProcessUtil_changePrioToLow 
    (JNIEnv *env, jclass ignored, jlong handle) { 

    SetPriorityClass((HANDLE)handle, IDLE_PRIORITY_CLASS); 
} 

確保編譯本地部分名爲ProcessUtil.dll庫。