如何更改进程优先级

3

I have

   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个回答

5

在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头文件(文件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的库。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接