Reference
How to handle InterruptedException
- Throw it directly
- If you can't throw it, call Thread.currentThread().interrupt()
- Check Thread.currentThread().isInterrupted() every while loop if you catch an InterruptedException within the loop block
Example:
This example shows how to handle InterruptedException, you can change code to check what will happen in other cases.
public class TestMain { public static void main(String[] params) { ThreadPoolExecutor e = (ThreadPoolExecutor) Executors.newCachedThreadPool(); MyRunnable r = new MyRunnable(); e.execute(r); System.out.println("shutdown"); e.shutdownNow(); System.out.println("shutdown done"); } private static class MyRunnable implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { System.out.println("sleep"); TimeUnit.HOURS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } } }