如何中断一个正在运行的线程

有时候中断一个正在运行的线程是一个比较重要的应用,但是貌似也是比较困难的事情。假设我们正在用第三方支付软件进行支付,点击确定以后,

由于某些原因需要取消这次支付,貌似现在还没有哪家的支付软件能够实现这样的功能,因为这个实在太困难了。开启一个线程去进行支付功能后,

即使做了一个这样的中断这个线程的功能,这个功能也不能保证钱在没有支付的前提下,线程被扼杀。

 

因为在Java的语言层面上没有提供有保证性的能够安全的终止线程的方法。而是采用了一种协商的方式来对线程进行中断。interrupte()方法就是中断

线程的方法,通过调用isInterrupted()和interrupted()方法都能来判断该线程是否被中断,它们的区别是,isInterrupted会保持中断状态;而

interrupted会清除中断状态。

 

线程在调用阻塞方法(sleep、join、wait、await)都会去检测这个中断状态,如果该线程已经被中断那么就会抛出InterruptedException,所以这些中断

方法都需要处理InterruptedException异常。抛出这个异常的作用是:(1)能够有时间处理中断请求;(2)清除中断状态

 1 public class MyThread extends Thread{
 2     public static void main(String[] args) {
 3           MyThread t=new MyThread();
 4           t.start();
 5           try {
 6             Thread.sleep(2000);//使开启的线程能够跑到执行体,否则线程还没到达执行体就被中断,此时判断中断状态肯定为true。
 7                                //那么就不能跑到执行体里面了
 8         } catch (InterruptedException e1) {
 9             e1.printStackTrace();
10         }
11           System.out.println("主线程中断开启线程");
12           t.interrupt();//主线程中断开启线程
13           System.out.println("等待中断请求");
14           try {
15             Thread.sleep(3000);//等待开启线程处理中断
16         } catch (InterruptedException e) {
17             e.printStackTrace();
18         }
19           System.out.println("应用程序结束");
20         
21     }
22     
23     
24     public void run() {
25         while(!Thread.currentThread().isInterrupted()) {
26                 System.out.println("线程正在运行。。");
27                 for(int i=0;i<100;i++) {
28                     System.out.println("i的值为:"+i);
29                 }
30                 
31                 try {
32                     Thread.sleep(2000);
33                 } catch (InterruptedException e) {
34                     System.out.println("开启线程被中断");
35                     Thread.currentThread().interrupt();//对中断请求的处理就是中断自己
36                 }
37         }
38     }
39 }

如果对中断请求的处理不是线程中断自己,那么线程将会一直运行下去。

posted on 2015-07-06 18:23  飞机说之代码也疯狂  阅读(2406)  评论(0编辑  收藏  举报