如何中断线程in Java

如何中断Java线程?查看API,香港服务器,不就是用interrupt()方法么?而线程是否已经中断则用Thread.currentThread().isInterrupted()返回true/false:

public class ThreadDemo extends Thread{ public static void main(String[] args) throws InterruptedException { Thread thread = new ThreadDemo(); thread.start(); thread.sleep(100); thread.interrupt(); //中断线程 } @Override public void run() { while(!Thread.currentThread().isInterrupted()) { System.out.println(“thread running”); try { Thread.sleep(100); }catch(InterruptedException e) { System.out.println(“InterruptedException”); } } System.out.println(“thread interrupted”); } }

运行结果:thread runningInterruptedExceptionthread runningthread runningthread runningthread running…

很快发现这方法似乎有问题,线程没有成功中断,于是在处理InterruptedException异常后调用break跳出while循环:

public class ThreadDemo extends Thread{ public static void main(String[] args) throws InterruptedException { Thread thread = new ThreadDemo(); thread.start(); thread.sleep(100); thread.interrupt(); //中断线程 } @Override public void run() { while(!Thread.currentThread().isInterrupted()) { System.out.println(“thread running”); try { Thread.sleep(100); }catch(InterruptedException e) { System.out.println(“InterruptedException”); break; } } System.out.println(“thread interrupted”); } }

运行结果(线程成功中断):thread runningInterruptedExceptionthread interrupted

接着在网上搜索了一下,写了一些例子研究后明白如何写一个可中断的线程。首先发现在调用线程的start()后,网站空间,立即调用interrupt()中断线程,线程停止了——被挡在while条件的外面:

用最少的浪费面对现在

如何中断线程in Java

相关文章:

你感兴趣的文章:

标签云: