关于java中怎么终止一个线程的执行

其实现在要对一个循环执行的线程关闭,对循环执行体设置执行标志是常见的方法。另外一种方法是使用interrupt方法中断线程方式关闭线程。

使用interrupt方法中断线程来退出线程

sleep wait io阻塞的情况下,对于这种线程退出的可以采用这种方法。主要方法原理就是使用interrupt方法设置中断状态,然后在catch代码块中执行如下逻辑。

catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e(LOG_TAG, "I'M exit exit ....");
e.printStackTrace();
break;
}

来退出线程。

给子线程设置标志位关闭子线程


package chapter2;

public class ThreadFlag extends Thread
{
    public volatile boolean exit = false;//设置停止标志位

    public void run()
    {
        while (!exit);
    }
    public static void main(String[] args) throws Exception
    {
        ThreadFlag thread = new ThreadFlag();
        thread.start();
        sleep(5000); // 主线程延迟5秒
        thread.exit = true;  // 设置终止子线程thread
        thread.join();
        System.out.println("线程退出!");
    }
}

第二个例子

public class AlternateStop extends Object implements Runnable {
    private volatile boolean stopRequested;//停止线程标志位
    private Thread runThread;//指向当前执行的线程
    public void run() {
        runThread = Thread.currentThread();
        stopRequested = false;
        int count = 0;
        while ( !stopRequested ) {
            System.out.println("Running ... count=" + count);
            count++;
            try {
                Thread.sleep(300);
            } catch ( InterruptedException x ) {
                Thread.currentThread().interrupt(); 
//当设置线程中断时,sleep方法会抛InterruptedException 异常,也可以在这里退出执行。
            }
        }

        System.out.println("stoped");
    }
    public void stopRequest() {//设置线程停止请求。
    //同时设置标志位和设置线程中断标志
        stopRequested = true;
        if ( runThread != null ) {
            runThread.interrupt();
        }
    }
    public static void main(String[] args) {
        AlternateStop as = new AlternateStop();
        Thread t = new Thread(as);
        t.start();
        try {
            Thread.sleep(2000);
        } catch ( InterruptedException x ) {
            // ignore
        }
        as.stopRequest();
    }
}

可能的运行结果如下:

Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6
stoped

参考文献

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值