-
public class Main extends Thread{ boolean stop = false; public static void main(String[] args) throws Exception { Thread thread = new Thread(new Main(),"My Thread2"); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Interrupting thread..." ); thread.interrupt(); System.out.println("线程是否中断:" + thread.isInterrupted()); Thread.sleep( 3000 ); System.out.println("Stopping application..." ); } public void run() { while(!stop){ System.out.println( "My Thread is running..." ); // 让该循环持续一段时间,使上面的话打印次数少点 long time = System.currentTimeMillis(); while((System.currentTimeMillis()-time < 1000)) { } if(Thread.currentThread().isInterrupted()) { return; } } System.out.println("My Thread exiting under request..." ); } }
线程中断 thread.interrupt()的用法
最新推荐文章于 2025-10-20 16:39:38 发布
本文通过一个具体的Java示例展示了如何使用线程的interrupt方法来优雅地终止一个正在运行的线程,并解释了如何在被中断的线程内部检查中断状态以确保资源能够正确释放。
1699

被折叠的 条评论
为什么被折叠?



