Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 411|回复: 0

[Java基础知识]获取Java VM中当前运行的所有线程

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-1 00:48:50 | 显示全部楼层 |阅读模式
    程序运行图:

       

    下面的静态方法可以用数组返回java VM中当前运行的所有线程
    public static Thread[] findAllThreads() {
    ThreadGroup group =  
    Thread.currentThread().getThreadGroup();
    ThreadGroup topGroup = group;

    // 遍历线程组树,获取根线程组
    while ( group != null ) {
    topGroup = group;
    group = group.getParent();
    }
    // 激活的线程数加倍
    int estimatedSize = topGroup.activeCount() * 2;
    Thread[] slackList = new Thread[estimatedSize];
    //获取根线程组的所有线程
    int actualSize = topGroup.enumerate(slackList);
    // copy into a list that is the exact size
    Thread[] list = new Thread[actualSize];
    System.arraycopy(slackList, 0, list, 0, actualSize);
    return list;
    }

           程序ThreadViewer.java以图形方式显示Java VM中当前运行的所有线程,它每隔5秒自动刷新一次,以保持获得最新信息。
      import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ThreadViewer extends JPanel {
            private ThreadViewerTableModel tableModel;
            public ThreadViewer() {
                    tableModel = new ThreadViewerTableModel();
                    JTable table = new JTable(tableModel);
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
                    TableColumnModel colModel = table.getColumnModel();
                    int numColumns = colModel.getColumnCount();
                    // manually size all but the last column
                    for ( int i = 0; i < numColumns - 1; i++ ) {
                            TableColumn col = colModel.getColumn(i);
                            col.sizeWidthToFit();
                            col.setPreferredWidth(col.getWidth() + 5);
                            col.setMaxWidth(col.getWidth() + 5);
                    }
                    JScrollPane sp = new JScrollPane(table);
                    setLayout(new BorderLayout());
                    add(sp, BorderLayout.CENTER);
            }
            public void dispose() {
                    tableModel.stopRequest();
            }
            protected void finalize() throws Throwable {
                    dispose();
            }
            public static JFrame createFramedInstance() {
                    final ThreadViewer viewer = new ThreadViewer();
                    final JFrame f = new JFrame("ThreadViewer");
                    f.addWindowListener(new WindowAdapter() {
                                    public void windowClosing(WindowEvent e) {
                                            f.setVisible(false);
                                            f.dispose();
                                            viewer.dispose();
                                    }
                            });
                    f.setContentPane(viewer);
                    f.setSize(500, 300);
                    f.setVisible(true);
                    return f;
            }
           
            public static void main(String[] args) {
                    JFrame f = ThreadViewer.createFramedInstance();
                    // For this example, exit the VM when the viewer
                    // frame is closed.
                    f.addWindowListener(new WindowAdapter() {
                                    public void windowClosing(WindowEvent e) {
                                            System.exit(0);
                                    }
                            });
                    // Keep the main thread from exiting by blocking
                    // on wait() for a notification that never comes.
                    Object lock = new Object();
                    synchronized ( lock ) {
                            try {
                                    lock.wait();
                            } catch ( InterruptedException x ) {
                            }
                    }
            }
    }
    [/code]
      import java.awt.*;
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ThreadViewerTableModel extends AbstractTableModel {
            private Object dataLock;
            private int rowCount;
            private Object[][] cellData;
            private Object[][] pendingCellData;
            // the column information remains constant
            private final int columnCount;
            private final String[] columnName;
            private final Class[] columnClass;
            // self-running object control variables
            private Thread internalThread;
            private volatile boolean noStopRequested;
            public ThreadViewerTableModel() {
                    rowCount = 0;
                    cellData = new Object[0][0];
                    // JTable uses this information for the column headers
                    String[] names = {
                            "Priority", "Alive",
                            "Daemon", "Interrupted",
                            "ThreadGroup", "Thread Name" };
                    columnName = names;                                                       
                                                   
                    // JTable uses this information for cell rendering
                    Class[] classes = {
                            Integer.class, Boolean.class,
                            Boolean.class, Boolean.class,
                            String.class, String.class };
                    columnClass = classes;
                    columnCount = columnName.length;
                    // used to control concurrent access
                    dataLock = new Object();
                    noStopRequested = true;
                    Runnable r = new Runnable() {
                                    public void run() {
                                            try {
                                                    runWork();
                                            } catch ( Exception x ) {
                                                    // in case ANY exception slips through
                                                    x.printStackTrace();
                                            }
                                    }
                            };
                    internalThread = new Thread(r, "ThreadViewer");
                    internalThread.setPriority(Thread.MAX_PRIORITY - 2);
                    internalThread.setDaemon(true);
                    internalThread.start();
            }
            private void runWork() {
                    // The run() method of transferPending is called by
                    // the event handling thread for safe concurrency.
                    Runnable transferPending = new Runnable() {
                                    public void run() {
                                            transferPendingCellData();
                                            // Method of AbstractTableModel that
                                            // causes the table to be updated.
                                            fireTableDataChanged();
                                    }
                            };
                    while ( noStopRequested ) {
                            try {
                                    createPendingCellData();
                                    SwingUtilities.invokeAndWait(transferPending);
                                    Thread.sleep(5000);
                            } catch ( InvocationTargetException tx ) {
                                    tx.printStackTrace();
                                    stopRequest();
                            } catch ( InterruptedException x ) {
                                    Thread.currentThread().interrupt();
                            }
                    }
            }
            public void stopRequest() {
                    noStopRequested = false;
                    internalThread.interrupt();
            }
            public boolean isAlive() {
                    return internalThread.isAlive();
            }
            private void createPendingCellData() {
                    // this method is called by the internal thread
                    Thread[] thread = findAllThreads();
                    Object[][] cell = new Object[thread.length][columnCount];
                    for ( int i = 0; i < thread.length; i++ ) {
                            Thread t = thread;
                            Object[] rowCell = cell;
                            rowCell[0] = new Integer(t.getPriority());
                            rowCell[1] = new Boolean(t.isAlive());
                            rowCell[2] = new Boolean(t.isDaemon());
                            rowCell[3] = new Boolean(t.isInterrupted());
                            rowCell[4] = t.getThreadGroup().getName();
                            rowCell[5] = t.getName();
                    }
                    synchronized ( dataLock ) {
                            pendingCellData = cell;
                    }
            }
            private void transferPendingCellData() {
                    // this method is called by the event thread
                    synchronized ( dataLock ) {
                            cellData = pendingCellData;
                            rowCount = cellData.length;
                    }
            }
            public int getRowCount() {
                    // this method is called by the event thread
                    return rowCount;
            }
           
            public Object getValueAt(int row, int col) {
                    // this method is called by the event thread
                    return cellData[row][col];
            }
            public int getColumnCount() {
                    return columnCount;
            }
            public Class getColumnClass(int columnIdx) {
                    return columnClass[columnIdx];
            }
            public String getColumnName(int columnIdx) {
                    return columnName[columnIdx];
            }
            public static Thread[] findAllThreads() {
                    ThreadGroup group =
                            Thread.currentThread().getThreadGroup();
                    ThreadGroup topGroup = group;
                    // traverse the ThreadGroup tree to the top
                    while ( group != null ) {
                            topGroup = group;
                            group = group.getParent();
                    }
                    // Create a destination array that is about
                    // twice as big as needed to be very confident
                    // that none are clipped.
                    int estimatedSize = topGroup.activeCount() * 2;
                    Thread[] slackList = new Thread[estimatedSize];
                    // Load the thread references into the oversized
                    // array. The actual number of threads loaded
                    // is returned.
                    int actualSize = topGroup.enumerate(slackList);
                    // copy into a list that is the exact size
                    Thread[] list = new Thread[actualSize];
                    System.arraycopy(slackList, 0, list, 0, actualSize);
                    return list;
            }
    }          [/code]

      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/1/004850156.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-10 21:04 , Processed in 0.411211 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表