Java 终止线程方法

我们一直以来都有一个错误的理解,认为interrupt会使线程停止运行,但事实上并非如此,调用一个线程的interrupt方法会把线程的状态改为中断态,但是interrupt方法只作用于那些因为执行了sleep、wait、join方法而休眠的线程,使他们不再休眠,同时会抛出InterruptedException异常。比如一个线程A正在sleep中,这时候另外一个程序里去调用A的interrupt方法,这时就会迫使A停止休眠而抛出InterruptedException异常;而如果线程A没有处于上面提到的三种休眠状态时被interrupt,这样就只是把线程A的状态改为interruptted,但是不会影响线程A的继续执行。
如何停止一个线程呢?用stop方法吗?肯定不行,这个方法由于不安全已经过时,不推荐使用,下面的例子提供了一个常用的停止线程的方法,例子中在线程中引入一个属性来控制,当需要停止线程时,只需要调用shutDownThread()方法即可,因为在线程的run()方法中会循环检测这个属性的值,为true正常运行,为false时不会进入循环,线程就可以结束.

public class TestStopThread
{
public static void main(String args[]) {
Runner r = new Runner() ;
Thread t = new Thread(r) ;
t.start() ;
for(int i=0 ;i<100 ;i++ ) {
if(i%10 == 0 )
System.out.println("Thread: i=" i) ;
}
System.out.println("Thread over ...") ;
r.shutDownThread() ;
}
}

class Runner implements Runnable
{
private boolean flag = true ;
public void run() {
int i = 0 ;
while(flag) {
System.out.println(i " ") ;
}
}
public synchronized void shutDownThread() {
flag = false ;
}
public synchronized boolean isShutDown() {
return flag;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值