Java如何停止线程,确定你知道的都是正确的么?

回想当年刚开始做Java开发的时候,如何停止线程运行可是难倒了一批人,停止线程的方法众说纷纭:

1. 调用Thread.stop() :

Thread thread = new Thread(){
    @Override
    public void run() {
        for (int i=0; i < 999 && !isCanceled; i++) {
            System.out.println("哈哈,我还没死...");
        }
    }
};
thread.start();

// kill you now
thread.stop();

点评: 不用多说,直接拉出去斩了

2. 线程外面定义boolean变量标识为是否已经取消,线程里每个循环地方加判断,变量变成了取消则停止循环:

private volatile boolean isCanceled = false;

new Thread(){
    @Override
    public void run() {
        for (int i=0; i < 999 && !isCanceled; i++) {
            System.out.println("哈哈,我还没死...");
        }
    }
}.start();

// kill thread
isCanceled = true;

点评: 太片面,线程里Thread.sleep(999999)取消不了的

3. 通过调用interrupt() :

Thread thread = new Thread(){
    @Override
    public void run() {
        sleep(99999);
        System.out.println("刚睡醒,我还没死!!!");
    }
};
thread.start();

// kill you now
thread.interrupt();

点评:也是太片面,for循环取消不了

4. 以上方案意思是有那么一点了,只是零零碎碎,如何将两个方案结合是今天的第一个话题。

在Thread内提供了一个方法叫interrupted(), 其返回值即告知是否线程被interrupt()执行过,简单说:无需自己定义boolean变量,可以用它代替,如果线程能被interrupt()而停止正好,如果是内部循环操作可以用它作为循环停止的条件:

Thread thread = new Thread(){
    @Override
    public void run() {
        for (int i=0; i < 999 && !Thread.interrupted(); i++) {
            System.out.println("哈哈,我还没死...");
        }
    }
};

其实,还有一种情况是停止不了的,类似socket/http通信这种不能被interrputted的情况,当然也有巧妙的办法:重载Thread的interrput()方法:

// 重载interrupt 通过关闭socket起到关闭线程的作用
@Override
public void interrupt() {
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

今天的第二个话题是,使用单个线程的情况在项目中极少,很多情况使用线程池托管的,那么线程池里如何停止某个task呢?

JDK5提供了ExecuteService,并通过Executors提供了多个候选的线程池选择方案,ExecutorService提交task有两种方式:execute()和submit(), 我们这里对submit()比较感兴趣,因为其中submit()会返回Feature,不管submit的是 Runnable还是Callable都会有Feature返回:

public interface ExecutorService extends Executor {
    /**
     * Submits a value-returning task for execution and returns a
     * Future representing the pending results of the task. The
     * Future's {@code get} method will return the task's result upon
     * successful completion.
     *
     * <p>
     * If you would like to immediately block waiting
     * for a task, you can use constructions of the form
     * {@code result = exec.submit(aCallable).get();}
     *
     * <p>Note: The {@link Executors} class includes a set of methods
     * that can convert some other common closure-like objects,
     * for example, {@link java.security.PrivilegedAction} to
     * {@link Callable} form so they can be submitted.
     *
     * @param task the task to submit
     * @param <T> the type of the task's result
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    <T> Future<T> submit(Callable<T> task);


    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's {@code get} method will
     * return {@code null} upon <em>successful</em> completion.
     *
     * @param task the task to submit
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    Future<?> submit(Runnable task);

    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's {@code get} method will
     * return the given result upon successful completion.
     *
     * @param task the task to submit
     * @param result the result to return
     * @param <T> the type of the result
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    <T> Future<T> submit(Runnable task, T result);
}

Feature对象提供了一系列API,如:

  1. cancel(boolean mayInterruptIfRunning) ;
  2. isCanceled();
  3. get();
  4. get(long timeout, TimeUnit unit);
  5. isDone()

看到第一个API,很是让人兴奋,难倒这真的可以一步到位?但很不好意思,依然不行,其实跟第一个话题的原理一摸一样,如果内部有阻塞线程的操作会因此而退出,如: wait(), join(), sleep() 等,但是遇到IO阻塞操作,比如进行socket通信,仅仅通过调用cancel(true)是不行的,不过可以重载interrupt() 关闭socket即可, 遇到大量循环也要通过Thread.interrupted()作为循环结束的条件:

class Task extends Thread{
    private Socket socket;

    public Task(){
        // init socket
    }

    // 重载interrupt 通过关闭socket起到关闭线程的作用
    @Override
    public void interrupt() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void func () {
    ExecutorService timer = Executors.newCachedThreadPool();

    Future<?> future = timer.submit(new Task());
    future.cancel(true);
}

好了,夜深了...回忆到此结束

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容

  • 先看几个概念:线程:进程中负责程序执行的执行单元。一个进程中至少有一个线程。多线程:解决多任务同时执行的需求,合理...
    yeying12321阅读 541评论 0 0
  • 【JAVA 线程】 线程 进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者...
    Rtia阅读 2,768评论 2 20
  • 李准基的小迷妹阅读 195评论 0 0
  • 苹果每一代产品的升级,是非常有节奏和讲究的。这是苹果取得成功的重要因素之一。苹果每12-18个月对产品进行一次升级...
    赵博思阅读 1,626评论 3 20
  • 鱼城的烟雨八百年 终于蕴育出这山脊的柔和 销弥了战火与仇恨 这高耸于蓝天下的山坡 在历史上抹了一笔 然后沉睡 然后...
    如歌的行板紫雪阅读 560评论 4 4