2014-12-03 131 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库。