Thread t1 = new Thread(() -> { while(!Thread.currentThread().isInterrupted()) { // do some work } }); t1.start(); // interrupt thread after some time try { Thread.sleep(5000); t1.interrupt(); } catch(InterruptedException e) { e.printStackTrace(); }
class MyThread extends Thread { public void run() { while(!isInterrupted()) { // do some work } } } MyThread t2 = new MyThread(); t2.start(); // interrupt thread after some time try { Thread.sleep(5000); t2.interrupt(); } catch(InterruptedException e) { e.printStackTrace(); }In this example, we create a new thread `t2` by inheriting from the Thread class and overriding the `run()` method to contain the work that needs to be done. The loop condition again uses `isInterrupted()` to check the interruption status. We interrupt the thread in the same way as before. Package library: `java.lang.Thread`