Throttling CPU/Memory usage of a Thread in Java?

前端 未结 9 2251
借酒劲吻你
借酒劲吻你 2020-12-07 13:00

I\'m writing an application that will have multiple threads running, and want to throttle the CPU/memory usage of those threads.

There is a similar question for C++,

9条回答
  •  轮回少年
    2020-12-07 13:11

    To reduce CPU, you want to sleep your threads inside of common if and while loops.

    while(whatever) {
        //do something
        //Note the capitol 'T' here, this sleeps the current thread.
        Thread.sleep(someNumberOfMilliSeconds);
    }
    

    Sleeping for a few hundred milliseconds will greatly reduce CPU usage with little to no noticeable result on performance.

    As for the memory, I'd run a profiler on the individual threads and do some performance tuning. If you out throttled the amount of memory available to thread I think an out of memory exception or starved thread is likely. I would trust the JVM to provide as much memory as the thread needed and work on reducing the memory usage by keeping only essential objects in scope at any given time.

提交回复
热议问题