首页 > 学院 > 开发设计 > 正文

文章标题

2019-11-08 02:38:36
字体:
来源:转载
供稿:网友

理解

当一个线程被阻塞的时候(io, sleep等),我们取消这种阻塞,这个时候就可以使用interrupt

例子和讲解

我们先看个例子,代码入下:

package com.renzhan;class TestRunnable implements Runnable{ public void run(){ while(true) { System.out.PRintln( "Thread is running..." ); System.out.println(Thread.currentThread().isInterrupted()); long time = System.currentTimeMillis();//取系统时间的毫秒数 while((System.currentTimeMillis()-time < 1000)) { //程序循环1秒钟,不同于sleep(1000)会阻塞进程。 } } }}public class App{ public static void main(String[] args){ Runnable r=new TestRunnable(); Thread th1=new Thread(r); th1.start(); th1.interrupt(); }}

代码的输出如下:

Thread is running...falseThread is running...trueThread is running...trueThread is running...trueThread is running...true

线程在调用interrupt 后,只是修改了他的状态,对线程的工作还是没有影响,这个是线程一直占据了cpu处于执行的状态。那么我们把线程的状态修改成sleep呢? 代码如下:

class TestRunnable implements Runnable{ public void run(){ try{ Thread.sleep(1000000); //这个线程将被阻塞1000秒 }catch(InterruptedException e){ e.printStackTrace(); //do more work and return. } }}

对应的输出如下:

java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at TestRunnable.run(App.java:6) at java.lang.Thread.run(Thread.java:745)

这个是因为线程当前处于阻塞状态,线程没有占用CPU,线程是不可能给自己的中断状态置位的。我们调用intrrupted 时候,这就会产生一个InterruptedException异常。正常我们就可以在异常处理中进行后续逻辑处理,我们也因此让进程变成了非阻塞状态。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表