如何更改优先级过程

时间:2014-12-03 15:26:44

标签: java windows process ffmpeg processbuilder

我有

   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();

如何在java中将进程优先级从“高”设置为“低”?

2 个答案:

答案 0 :(得分:4)

无法在Java中设置进程的优先级 只有线程优先权。
但您可以使用系统命令以指定的优先级运行进程:
Linux:new ProcessBuilder("nice", "-n", "10", "somecommand", "arg1", "arg2");
Windows:new ProcessBuilder("cmd", "/C start /B /belownormal /WAIT javaws -sdasd");

答案 1 :(得分: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标头(文件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的库。

相关问题