How do I "gracefully" terminate thread T2 in a thread T1? */ @Slf4j public class Test4 { public static void main(String[] args) throws InterruptedException { TwoPhaseTermination tpt = new TwoPhaseTermination(); tpt.start(); Thread.sleep(3500); tpt.stop(); } @Slf4j static class TwoPhaseTermination{ private Thread monitor; public void start() { monitor = new Thread(() -> { while (true) { Thread current = Thread.currentThread(); If (current.isinterrupted ()) {log.info(" after "); break; } try { Thread.sleep(2000); Log.info (" Perform monitoring record "); } catch (InterruptedException e) {log.info(" thread interrupted "); // If the thread is interrupted during sleep, an exception will be thrown; The interrupt flag is reset to false; So reset the interrupt flag current-.interrupt (); }}}); monitor.start(); } private void stop() { monitor.interrupt(); }}}Copy the code