java线程可以终止吗?

Posted on 2009-06-06 08:53 thui 阅读(3586) 评论(0)  编辑  收藏 所属分类: java技术
今天写了一个小程序,
public class ThreadTest extends Thread {
    public static void main(String[] args) throws InterruptedException {
        ThreadTest tt = new ThreadTest();
        tt.start();
        tt.interrupt();
        System.out.println(tt.isInterrupted());
    }
    public void run() {
        int i=0;
        while (i<9) {
            System.out.println("thread is running!");
            i ;
        }
    }
}
哈哈,满怀信心的想执行完这个程序线程就会被中断了,可是现实总是很残忍,程序运行到底,thread is running打印了9次,靠,怪了,为什么会这样?为了彻底理解这个奥秘,我google了一下,总算找到了答案。
原来我们一直以来都有一个错误的理解,认为interrupt会使线程停止运行,但事实上并非如此,调用一个线程的interrupt方法会把线程的状态改为中断态,但是interrupt方法只作用于那些因为执行了sleep、wait、join方法而休眠的线程,使他们不再休眠,同时会抛出InterruptedException异常,什么意思呢?加入一个线程A正在sleep中,这时候另外一个程序里去调用A的interrupt方法,这时就会迫使A停止休眠而抛出InterruptedException异常,上面的例子中线程ThreadTest在没有处于上面提都的三种休眠状态时被interrupt,这时只是把tt的状态改为interruptted,但是不会影响tt的继续执行。所以我们看到了上面的结果。
那么我们到底该如何停止一个线程呢?用stop方法吗?肯定不行,这个方法由于不安全已经过时,不推荐使用,下面的例子提供了一个优雅且常用的停止线程的方法,
例子中在线程中引入一个属性来控制,当需要停止线程时,只需要调用shutDown()方法即可,因为在线程的run方法中会循环检测这个属性的值,为true正常运行,为false时不会进入循环,线程就可以结束
public class TestStop
{
    public static void main(String args[]) {
        Runner r = new Runner() ;
        Thread tr = new Thread(r) ;
        tr.start() ;
        for(int i=0 ;i<100000 ;i ) {
            if(i%10000 == 0 )
                System.out.println("in thread main i=" i) ;
        }
        System.out.println("Thread main is over") ;
        r.shutDown() ;
    }
}
class Runner implements Runnable
{
    private boolean flag = true ;
    public void run() {
        int i = 0 ;
        while(flag) {
            System.out.println(i " ") ;
        }
    }
    public synchronized void shutDown() {
        flag = false ;
    }
    public synchronized boolean isShutDown() {
        return flag;
    }
}

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 11, comments - 8, trackbacks - 0, articles - 4

Copyright © thui