android 如何中断一个子线程

需求场景:文件下载(下载,暂停,取消)

这里我们的研究对象时Thread
下载线程Thread 我们暂且叫做 a线程(下载线程)

1.下载

我们只需要开启一个a线程去下载文件资源

下面代码只是模拟下载(下载的具体代码,百度 Google就可以了)

  DownloadThread t= new DownloadThread();
  t.start();

DownloadThread 类

    class DownloadThread extends Thread{
        @Override
        public void run() {
            super.run();
            while ("读取文件流"){
//               这里是写文件流的操作
            }
        }
    }

2.暂停下载(其实就是暂停一个线程)

我们如何去停止一个正在下载的线程呢?
    1.Thread.stop 这个方法可以停止一个正在运行的线程,不过这种停止线程的操作是不安全的,java 也将这个方法声明为@Deprecated
    2.通过自己加标示位,通过标示位来结束run方法,从来结束整个线程
    3.Thread.interrupt() 如果你的线程中有Sleep方法则会抛出InterruptedException异常 通过捕获此异常进行终止run方法。如果是非阻塞线程你可以用Thread.currentThread().isInterrupted()状态来结束run方法

java 中的Thread.stop方法

    /**
     * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is
     * resumed if it was suspended and awakened if it was sleeping, so that it
     * can proceed to throw ThreadDeath.
     *
     * @deprecated because stopping a thread in this manner is unsafe and can
     * leave your application and the VM in an unpredictable state.
     */
    @Deprecated
    public final void stop() {
        stop(new ThreadDeath());
    }

在线程中设置停止标志位

    class DownloadThread extends Thread{
        boolean isStop;
        @Override
        public void run() {
            super.run();
            while (!isStop){
//               这里是读文件流 和写文件流的操作
            }
        }
        public void stopDownload(){
            isStop=true;

        }
    }

方法调用

        DownloadThread t= new DownloadThread();
        t.start();
        t.stopDownload();

使用Thread.interrupt()方法

    DownloadThread t= new DownloadThread();
    t.start();
    t.interrupt();

    class DownloadThread extends Thread{
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()){
//               这里是读文件流 和写文件流的操作
            }
        }
    }

停止线程池中的线程

ExecutorService mExecutors=Executors.newCachedThreadPool();
//利用mExecutors.submit方法进行开启一个线程 获取到一个Future<?>对象
Future<?> connectThreadFuture=mExecutors.submit(connectThread)
//Future<?>对象提供中断线程的方法cancel 具体参数大家看api解释
connectThreadFuture.cancel(true);//停止线程的方法

自己撸的一个多任务多线程断点下载的库,里面有暂停下载任务就是用了上面的方法,大家可以参考下
https://github.com/qinweiforandroid/QDownload

结束语

文章有什么不对的地方,还请大家斧正.
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值