Online Java Compiler By
JavaTpoint.com
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.lang.Thread; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; public class ThreadPoolExecutorgetKeepAliveTimeExample1 { public static void main(String[] args) { Task9 task1 = new Task9("t1"); System.out.println("Starting threads"); ThreadPoolExecutor tExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); System.out.println(" Before execute Currently executing threads: "+ tExecutor.getActiveCount()); tExecutor.execute(task1); // start task1 System.out.println(" get keep alive time: "+ tExecutor.getKeepAliveTime(TimeUnit.DAYS)); tExecutor.shutdown(); // shutdown worker threads System.out.println("Threads started, main ends\n"); } } class Task9 implements Runnable { private final String threadName; public Task9(String threadName) { this.threadName = threadName; } @Override public void run() { for(int i=0 ; i<=10;i++) { if(i<5) { try { System.out.println("Thread sleeping for 1000 i=" +i); Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Task9.class.getName()).log(Level.SEVERE, null, ex); } } else{ System.out.println(" now i > 5 :"); break; } } } }
Output