java根据线程id获取线程

    /**
     * 通过线程组获得线程
     *
     * @param threadId
     * @return
     */
    public static Thread findThread(long threadId) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while(group != null) {
            Thread[] threads = new Thread[(int)(group.activeCount() * 1.2)];
            int count = group.enumerate(threads, true);
            for(int i = 0; i < count; i++) {
                if(threadId == threads[i].getId()) {
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }

  线程id可以在开启线程时通过 thread.getId()进行获取并存入内存。

  随后可在其他位置通过线程id获取到线程并进行各种操作。

  中断线程的方法:https://blog.csdn.net/aliahhqcheng/article/details/8793843

  这里写一个我使用的中断线程的方法:

try {
            //进入线程后先睡眠60秒
            Thread.sleep(60*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("检测到线程中断,关闭线程");
            return;
        }

  线程开始时先进入sleep。如果在sleep的过程中检测到线程的状态为中断会报出异常,这时候将线程断掉就好了。

原文地址:https://www.cnblogs.com/emojio/p/11132354.html