简体   繁体   English

跨平台更改Java进程优先级的方法

[英]Cross-platform way to change java process priority

I need to invoke .jar file in separate JVM from another java application, and it very CPU-consuming, so it should run with background priority in order not to affect the rest of the system. 我需要在与另一个Java应用程序分开的JVM中调用.jar文件,它非常占用CPU,因此应以后台优先级运行,以免影响系统的其余部分。 Is there any cross-platform method to do this? 有没有跨平台的方法可以做到这一点?

The simple answer is that there is no portable way to change the priority of a Process in Java. 简单的答案是,没有可移植的方法来更改Java中进程的优先级。 (Threads - yes, Processes - no.) (线程-是,进程-否。)

If your Java application needs to start a new JVM to run the CPU intensive application, then the chances are that it is already not entirely portable. 如果您的Java应用程序需要启动一个新的JVM来运行CPU密集型应用程序,那么很可能它不是完全可移植的。 For example, you will typically need to give the pathname of the java command (or equivalent), a -cp argument (or equivalent), system specific JVM options, and so on. 例如,您通常需要提供java命令的路径名(或等效项),- -cp参数(或等效项),系统特定的JVM选项,等等。

So, assuming that the command to launch the JVM is already non-portable, it should hardly matter if you replace the command with a wrapper script that does OS-specific things to change the priority of the launched process. 因此,假设启动JVM的命令已经不可移植,那么用一个包装程序脚本替换该命令就没关系了,该脚本执行特定于OS的操作来更改启动进程的优先级。 (For example, for UNIX or Linux you could simply use nice to launch the JVM.) (例如,对于UNIX或Linux,您可以简单地使用nice启动JVM。)

I don't know the way to set the priority for an external process. 我不知道为外部进程设置优先级的方法。 Thread however has a setPriority method, so if you control the target application, you could perhaps add a switch, telling the application to set its own priority to minimum: 但是, Thread具有setPriority方法,因此,如果您控制目标应用程序,则可以添加一个开关,告诉应用程序将其自身的优先级设置为最小:

theThread.setPriority(Thread.MIN_PRIORITY);

If it still affects the system, I suggest you interleave some short sleep ing to offload the cpu. 如果仍然影响系统,建议您插入一些短暂的sleep以减轻CPU负担。


Another option: 另外一个选项:

If you put the target .jar in the classpath of the "initiating" application, you can simply invoke the main -method of the jar-file in a newly created thread, and then set the priority using the above method. 如果将目标.jar放在“正在启动”应用程序的类路径中,则可以在新创建的线程中简单地调用jar文件的main方法,然后使用上述方法设置优先级。 (This should work even if you don't control the source-code of the target jar file.) (即使您不控制目标jar文件的源代码,这也应该起作用。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM