黑马程序员技术交流社区
标题:
java结束线程问题?
[打印本页]
作者:
曾辉
时间:
2012-2-9 14:14
标题:
java结束线程问题?
在主线程中启动了一个子线程
先已知子线程被阻塞,是因为url连接建立,阻塞在读取数据方面,因此通过标识符判断使子线程自动结束的方法无法使用了先就请教,如何在主线程中直接kill掉这个子线程了
使用了t.stop()//t为子线程引用
或者
try {
t.sleep(300);
} catch (InterruptedException x) {
t.interrupt();//中断线程
}
2个方法均无法直接kill掉线程t,因为在执行方法之前之后,执行t.isAlive()均为true
不知道现在有没有其他别的方法能够使用了
作者:
maochong
时间:
2012-2-9 18:31
调用一个线程的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;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2