Thread t = new Thread(() -> { try { while (!Thread.interrupted()) { // Do some work } } catch (InterruptedException e) { // Handle the exception } }); // Interrupt the thread after 5 seconds try { Thread.sleep(5000); t.interrupt(); } catch (InterruptedException e) { // Handle the exception }
Thread t = new Thread(() -> { while (true) { if (Thread.currentThread().isInterrupted()) { // Handle the interruption break; } // Do some work } }); // Interrupt the thread after 5 seconds try { Thread.sleep(5000); t.interrupt(); } catch (InterruptedException e) { // Handle the exception }In this example, a new thread is created that performs some work until it is interrupted. The worker thread checks its interruption status in the loop and handles it when it is interrupted. The main thread sleeps for 5 seconds and then interrupts the worker thread. Java Thread interrupt method is a part of the java.lang package library.