java线程之sleep、interrupt方法

来源:互联网 发布:计算总金额排名sql语句 编辑:程序博客网 时间:2024/04/29 11:15

下面是一个测试interrupt方法的小代码:

package cn.edu.ustc.thread;import java.util.Date;public class TestInterrupt {public static void main(String[] args){MyThread thread = new MyThread();thread.start();try{Thread.sleep(10000);}catch(InterruptedException e){}thread.interrupt();}}class MyThread extends Thread{public void run(){while(true){System.out.println("==="+ new Date()+"===");try {sleep(1000);} catch (InterruptedException e) {return;}}}}
interrupt方法相当于线程睡着的时候“泼凉水”,在上面代码中,主线程睡醒之后,调用thread线程的interrupt方

法,catch到InteruptedException,return,程序运行结束,即子线程结束。这是停住线程的一种方法。但是不好,

因为可能导致子线程运行过程中有些资源来不及关闭。

对上述代码稍作改进如下:

package cn.edu.ustc.thread;import java.util.Date;public class TestInterrupt {public static void main(String[] args){MyThread thread = new MyThread();thread.start();try{Thread.sleep(10000);}catch(InterruptedException e){}thread.setFlag(false);}}class MyThread extends Thread{private boolean flag = true;public void run(){while(flag){System.out.println("==="+ new Date()+"===");try {sleep(1000);} catch (InterruptedException e) {return;}}}public boolean isFlag() {return flag;}public void setFlag(boolean flag) {this.flag = flag;}}
稍做说明:给线程增加一个标志位flag,通过改变flag的状态控制线程,这样会比上面稍微好一点。


原创粉丝点击