java根據線程的id去獲取線程


 public static void main(String[] args) {
        Thread t = new Thread(new InnerRunnable());
        t.start();
        System.out.println("        thread: " + t);
        long threadId = t.getId();
        
        // 一:通過線程組遍歷獲得線程
        Thread s = findThread(threadId);
        System.out.println("   find thread: " + s);
        System.out.println("current thread: " + Thread.currentThread());
               
        
        // 二:通過 JMX 可以通過線程 ID 獲得線程信息
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        ThreadInfo info = tmx.getThreadInfo(threadId);
        System.out.println(info.getThreadState());
        
        
        s.interrupt();
    }

    /**
     * 通過線程組獲得線程
     *
     * @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;
    }

    private static class InnerRunnable implements Runnable {

        private int i = 0;

        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(i++);
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                System.out.println("mythread is interrupted!");
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM