Java ThreadPoolExecutor setKeepAliveTime() MethodThe setKeepAliveTime() method of ThreadPoolExecutor class sets the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated. SyntaxParametersTime - the time to wait. The zero time value will cause excess threads to terminate immediately after executing tasks. unit - the time unit of the time argument. ReturnNA ThrowIllegalArgumentException - if time less than zero or if time is zero and allowsCoreThreadTimeOut Example 1Test it NowOutput: Starting threads Before execute Currently executing threads: 0 get keep alive time: 0 Threads started, main ends Thread sleeping for 1000 i=0 Thread sleeping for 1000 i=1 Thread sleeping for 1000 i=2 Thread sleeping for 1000 i=3 Thread sleeping for 1000 i=4 now i > 5 : Example 2Test it NowOutput: get Keep alive Time: 2 Running Thread Name: pool-1-thread-2 Running Thread Name: pool-1-thread-1 Completed Thread Name: pool-1-thread-1 Completed Thread Name: pool-1-thread-2
Next TopicJava ThreadPoolExecutor
|