子线程杀掉主线程

如果线程执行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 + "]";
        }
    }

}
复制代码

 

posted @   VipSoft  阅读(174)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2012-06-10 Linux 下 DNS的配置
点击右上角即可分享
微信分享提示