• 子线程杀掉主线程


    如果线程执行N久还没结束,就想把它杀掉,把线程留给其它任务使用。

    思路:主线程执行时,开一个子线程来监控它,看是否执行完成。如果没有执行完成就把它干了,执行完了就不管。

    package com.vipsoft.Thread;
    
    public class ThreadMain {
    
        public static void main(String[] args) {
            for (int i = 1; i <= 5; i++) {
                Thread mainT = Thread.currentThread();
                String threadName = "Thread-" + i;
                SubThread st = new SubThread(threadName, mainT);
                Thread thread = new Thread(st);
                thread.start();
                try {
                    System.out.println("主线程,开始 " + threadName);
                    Thread.sleep(i * 1000);
                    st.setDone();
                    System.out.println("主线程,执行完成 " + threadName);
                } catch (InterruptedException e) {
                    System.out.println("主线程,被打断 " + threadName);
                }
            }
        }
    
    
        static class SubThread implements Runnable {
            private String name;
            private Thread mainT;
    
            //如果完成了就不用杀了。
            private boolean isDone;
    
            public void setDone() {
                isDone = true;
            }
    
            public SubThread(String name, Thread mainT) {
                this.name = name;
                this.mainT = mainT;
            }
    
            @Override
            public void run() {
                try {
                    System.out.println("子线程,正在监控主进程 " + name);
                    Thread.sleep(2000);
                    //时间到了,主线程还没有完成就干掉。
                    if (!isDone) {
                        mainT.interrupt();
                        System.out.println("子线程,干掉了主进程(超时了) " + name);
                    }
                } catch (InterruptedException e) {
                    System.out.println("子线程,被打断");
                    return;
                }
            }
    
            @Override
            public String toString() {
                return "MyTask [name=" + this.name + "]";
            }
        }
    
    }
  • 相关阅读:
    汉语-成语:鳏寡孤惸
    汉语-汉字:谶
    汉语-汉字:彘
    汉语-汉字:齑、齏
    mac下配置adb
    常见的开发语言(或IT技术)一览
    SurfaceView的经典写法
    HDU4499 Cannon DFS 回溯的应用
    什么是Pro*C/C++,嵌入式SQL,第一个pro*c程序,pro*c++,Makefile,Proc增删改查
    Cocos开发中性能优化工具介绍之使用Windows任务管理器
  • 原文地址:https://www.cnblogs.com/vipsoft/p/16363184.html
Copyright © 2020-2023  润新知