2019-04-01

Thread 停止的方式

线程停止的3种方式:

第一种方式:interrupt()

interrupted();调用此方法仅仅是在当前线程中打一个停止的标记,并不是正在的停止线程

判断当前线程是否停止状态:

[if !supportLists]1、[endif]this.interrupted() 静态方法,测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能

[if !supportLists]2、[endif]this.isInterrupted() 普通public方法,测试线程Thread对象是否已经中断状态,但不清除标志。

第二种方式:异常法

private

class ExceptionThread extends Thread {

    @Override

    public void run() {

        super.run();

        try {

            for (inti = 0; i < Integer.MAX_VALUE; i++){

                Log.e("ExceptionThread", "i: " + i);

                if (this.isInterrupted()) {

                    Log.e("ExceptionThread", "已经停止了......");

                throw new InterruptedException();

                }

                Log.e("ExceptionThread", "我在for循环下面");

            }

        } catch (InterruptedException e) {

            Log.e("InterruptedException", "我在 catch InterruptedException");

            e.printStackTrace();

        }

    }

}


第三种方式:return

While(true) {

If (thread.isInterrupted()) {

   return;

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容