子线程杀掉主线程

如果线程执行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 @ 2022-06-10 14:42  VipSoft  阅读(172)  评论(0编辑  收藏  举报