函数有嵌套的情况下如何停止线程?

函数有嵌套的情况下如何停止线程

void thread_start(){
    new Thread(){
        public void run(){
            callMethod1();
            callMethod2();
            callMethod3();
            callMethod4();
            callMethod5();
            callMethod6();
        }
    }.start();
} 
void callMethod5(){
    foo1();
    foo2();
    foo3();
    foo4();
    foo5();
    ...
    foo66();    // 怎么在这里停止线程呢
    ...
    foo98();
    foo99();
    foo100();;
}


怎么停止线程 因为实际情况嵌套在多个场景下,或者说有什么解决方式,

阅读 3.1k
4 个回答

自己实现一个用于退出线程的异常类,foo66里面如果想退出线程,就直接抛出这个异常,然后在run里面抓异常return就可以。

public static class StopException extends RuntimeException {
    public StopException (){
        super();
    }

    public StopException (String message) {
        super(message);
    }

    public StopException (String message, Throwable cause) {
        super(message, cause);
    }
}

void thread_start(){

new Thread(){
    public void run(){
        try{
            callMethod1();
            callMethod2();
            callMethod3();
            callMethod4();
            callMethod5();
            callMethod6();
        }catch(StopException ex){
            return;
        }
    }
}.start();

}
void callMethod5(){

foo1();
foo2();
foo3();
foo4();
foo5();
...
foo66();    // 怎么在这里停止线程呢
throw new StopException();// 这里停止线程
...
foo98();
foo99();
foo100();;

}

一楼正解!!!

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        test.threadStart();
    }
    
    public void threadStart() {
        new Thread() {
            @Override
            public void run() {
                callMethod5();
                if (Thread.interrupted()) {
                    System.out.println("thread was interrupted.");
                    return;
                }
                callMethod6();
            }
        }.start();
    }

    public void callMethod6() {
        System.out.println(6);
    }

    public void callMethod5() {
        System.out.println(5.1);
        // 模拟中断条件,50% 几率
        if (Math.random() > 0.5) {
            Thread.currentThread().interrupt();
            return;
        }
        System.out.println(5.2);
    }
}

@殃殃

问题本质是如何优雅的关闭掉一个线程:

  1. 通过在foo66()方法中设置volatile变量,同一时间只能有一个变量修改volatile变量,满足变量条件时,return掉。
  2. 用interrupt方式,响应中断,终止线程。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题