您好,欢迎访问一九零五行业门户网

Java 实例 - 中断线程

以下实例演示了如何使用interrupt()方法来中断线程并使用 isinterrupted() 方法来判断线程是否已中断:
/* author by w3cschool.cc main.java */ public class main extends object implements runnable { public void run() { try { system.out.println("in run() - 将运行 work2() 方法"); work2(); system.out.println("in run() - 从 work2() 方法回来"); } catch (interruptedexception x) { system.out.println("in run() - 中断 work2() 方法"); return; } system.out.println("in run() - 休眠后执行"); system.out.println("in run() - 正常离开"); } public void work2() throws interruptedexception { while (true) { if (thread.currentthread().isinterrupted()) { system.out.println("c isinterrupted()=" + thread.currentthread().isinterrupted()); thread.sleep(2000); system.out.println("d isinterrupted()=" + thread.currentthread().isinterrupted()); } } } public void work() throws interruptedexception { while (true) { for (int i = 0; i < 100000; i++) { int j = i * 2; } system.out.println("a isinterrupted()=" + thread.currentthread().isinterrupted()); if (thread.interrupted()) { system.out.println("b isinterrupted()=" + thread.currentthread().isinterrupted()); throw new interruptedexception(); } } } public static void main(string[] args) { main si = new main(); thread t = new thread(si); t.start(); try { thread.sleep(2000); } catch (interruptedexception x) { } system.out.println("in main() - 中断其他线程"); t.interrupt(); system.out.println("in main() - 离开"); } }
以上代码运行输出结果为:
in run() - 将运行 work2() 方法 in main() - 中断其他线程 in main() - 离开 c isinterrupted()=true in run() - 中断 work2() 方法
以上就是java 实例 - 中断线程的内容。
其它类似信息

推荐信息