获取 Java VM 中当前运行的所有线程

来源:互联网 发布:ios9.3.5越狱优化 编辑:程序博客网 时间:2024/05/19 22:28

http://blog.csdn.net/defonds/article/details/4848853


程序运行图:

程序运行效果图
        下面的静态方法可以用数组返回 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 中当前运行的所有线程,它每隔 2 秒自动刷新一次,以保持获得最新信息。程序 ThreadViewer.java 源代码:

[java] view plaincopyprint?
  1. package thread;  
  2. import java.awt.*;  
  3. import java.awt.event.*;  
  4. import javax.swing.*;  
  5. import javax.swing.table.*;  
  6. public class ThreadViewer extends JPanel {  
  7.     private ThreadViewerTableModel tableModel;  
  8.     public ThreadViewer() {  
  9.         tableModel = new ThreadViewerTableModel();  
  10.         JTable table = new JTable(tableModel);  
  11.         table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);  
  12.         TableColumnModel colModel = table.getColumnModel();  
  13.         int numColumns = colModel.getColumnCount();  
  14.         // manually size all but the last column  
  15.         for ( int i = 0; i < numColumns - 1; i++ ) {  
  16.             TableColumn col = colModel.getColumn(i);  
  17.             col.sizeWidthToFit();  
  18.             col.setPreferredWidth(col.getWidth() + 5);  
  19.             col.setMaxWidth(col.getWidth() + 5);  
  20.         }  
  21.         JScrollPane sp = new JScrollPane(table);  
  22.         setLayout(new BorderLayout());  
  23.         add(sp, BorderLayout.CENTER);  
  24.     }  
  25.     public void dispose() {  
  26.         tableModel.stopRequest();  
  27.     }  
  28.     protected void finalize() throws Throwable {  
  29.         dispose();  
  30.     }  
  31.     public static JFrame createFramedInstance() {  
  32.         final ThreadViewer viewer = new ThreadViewer();  
  33.         final JFrame f = new JFrame("ThreadViewer");  
  34.         f.addWindowListener(new WindowAdapter() {  
  35.                 public void windowClosing(WindowEvent e) {  
  36.                     f.setVisible(false);  
  37.                     f.dispose();  
  38.                     viewer.dispose();  
  39.                 }  
  40.             });  
  41.         f.setContentPane(viewer);  
  42.         f.setSize(500300);  
  43.         f.setVisible(true);  
  44.         return f;  
  45.     }  
  46.       
  47.     public static void main(String[] args) {  
  48.         JFrame f = ThreadViewer.createFramedInstance();  
  49.         // For this example, exit the VM when the viewer  
  50.         // frame is closed.  
  51.         f.addWindowListener(new WindowAdapter() {  
  52.                 public void windowClosing(WindowEvent e) {  
  53.                     System.exit(0);  
  54.                 }  
  55.             });  
  56.         // Keep the main thread from exiting by blocking  
  57.         // on wait() for a notification that never comes.  
  58.         Object lock = new Object();  
  59.         synchronized ( lock ) {  
  60.             try {  
  61.                 lock.wait();  
  62.             } catch ( InterruptedException x ) {  
  63.             }  
  64.         }  
  65.     }  
  66. }  

        程序 ThreadViewerTableModel.java 源代码:

[java] view plaincopyprint?
  1. package thread;  
  2. import java.awt.*;  
  3. import java.lang.reflect.*;  
  4. import javax.swing.*;  
  5. import javax.swing.table.*;  
  6. public class ThreadViewerTableModel extends AbstractTableModel {  
  7.     private Object dataLock;   
  8.     private int rowCount;  
  9.     private Object[][] cellData;  
  10.     private Object[][] pendingCellData;  
  11.     // the column information remains constant  
  12.     private final int columnCount;  
  13.     private final String[] columnName;  
  14.     private final Class[] columnClass;  
  15.     // self-running object control variables  
  16.     private Thread internalThread;  
  17.     private volatile boolean noStopRequested;  
  18.     public ThreadViewerTableModel() {  
  19.         rowCount = 0;  
  20.         cellData = new Object[0][0];  
  21.         // JTable uses this information for the column headers  
  22.         String[] names = {   
  23.             "Priority""Alive",   
  24.             "Daemon""Interrupted",   
  25.             "ThreadGroup""Thread Name" };  
  26.         columnName = names;                           
  27.                           
  28.         // JTable uses this information for cell rendering  
  29.         Class[] classes = {   
  30.             Integer.class, Boolean.class,   
  31.             Boolean.class, Boolean.class,   
  32.             String.class, String.class };  
  33.         columnClass = classes;  
  34.         columnCount = columnName.length;  
  35.         // used to control concurrent access  
  36.         dataLock = new Object();   
  37.         noStopRequested = true;  
  38.         Runnable r = new Runnable() {  
  39.                 public void run() {  
  40.                     try {  
  41.                         runWork();  
  42.                     } catch ( Exception x ) {  
  43.                         // in case ANY exception slips through  
  44.                         x.printStackTrace();   
  45.                     }  
  46.                 }  
  47.             };  
  48.         internalThread = new Thread(r, "ThreadViewer");  
  49.         internalThread.setPriority(Thread.MAX_PRIORITY - 2);  
  50.         internalThread.setDaemon(true);  
  51.         internalThread.start();  
  52.     }  
  53.     private void runWork() {  
  54.         // The run() method of transferPending is called by   
  55.         // the event handling thread for safe concurrency.  
  56.         Runnable transferPending = new Runnable() {  
  57.                 public void run() {  
  58.                     transferPendingCellData();  
  59.                     // Method of AbstractTableModel that   
  60.                     // causes the table to be updated.  
  61.                     fireTableDataChanged();   
  62.                 }  
  63.             };  
  64.         while ( noStopRequested ) {  
  65.             try {  
  66.                 createPendingCellData();  
  67.                 SwingUtilities.invokeAndWait(transferPending);  
  68.                 Thread.sleep(2000);  
  69.             } catch ( InvocationTargetException tx ) {  
  70.                 tx.printStackTrace();  
  71.                 stopRequest();  
  72.             } catch ( InterruptedException x ) {  
  73.                 Thread.currentThread().interrupt();   
  74.             }  
  75.         }  
  76.     }  
  77.     public void stopRequest() {  
  78.         noStopRequested = false;  
  79.         internalThread.interrupt();  
  80.     }  
  81.     public boolean isAlive() {  
  82.         return internalThread.isAlive();  
  83.     }  
  84.     private void createPendingCellData() {  
  85.         // this method is called by the internal thread  
  86.         Thread[] thread = findAllThreads();  
  87.         Object[][] cell = new Object[thread.length][columnCount];  
  88.         for ( int i = 0; i < thread.length; i++ ) {  
  89.             Thread t = thread[i];  
  90.             Object[] rowCell = cell[i];  
  91.             rowCell[0] = new Integer(t.getPriority());  
  92.             rowCell[1] = new Boolean(t.isAlive());  
  93.             rowCell[2] = new Boolean(t.isDaemon());  
  94.             rowCell[3] = new Boolean(t.isInterrupted());  
  95.             rowCell[4] = t.getThreadGroup().getName();  
  96.             rowCell[5] = t.getName();  
  97.         }  
  98.         synchronized ( dataLock ) {  
  99.             pendingCellData = cell;  
  100.         }  
  101.     }  
  102.     private void transferPendingCellData() {  
  103.         // this method is called by the event thread  
  104.         synchronized ( dataLock ) {  
  105.             cellData = pendingCellData;  
  106.             rowCount = cellData.length;  
  107.         }  
  108.     }  
  109.     public int getRowCount() {  
  110.         // this method is called by the event thread  
  111.         return rowCount;  
  112.     }  
  113.       
  114.     public Object getValueAt(int row, int col) {  
  115.         // this method is called by the event thread  
  116.         return cellData[row][col];  
  117.     }  
  118.     public int getColumnCount() {  
  119.         return columnCount;  
  120.     }  
  121.     public Class getColumnClass(int columnIdx) {  
  122.         return columnClass[columnIdx];  
  123.     }  
  124.     public String getColumnName(int columnIdx) {  
  125.         return columnName[columnIdx];  
  126.     }  
  127.     public static Thread[] findAllThreads() {  
  128.         ThreadGroup group =   
  129.             Thread.currentThread().getThreadGroup();  
  130.         ThreadGroup topGroup = group;  
  131.         // traverse the ThreadGroup tree to the top  
  132.         while ( group != null ) {  
  133.             topGroup = group;  
  134.             group = group.getParent();  
  135.         }  
  136.         // Create a destination array that is about  
  137.         // twice as big as needed to be very confident  
  138.         // that none are clipped.  
  139.         int estimatedSize = topGroup.activeCount() * 2;  
  140.         Thread[] slackList = new Thread[estimatedSize];  
  141.         // Load the thread references into the oversized  
  142.         // array. The actual number of threads loaded   
  143.         // is returned.  
  144.         int actualSize = topGroup.enumerate(slackList);  
  145.         // copy into a list that is the exact size  
  146.         Thread[] list = new Thread[actualSize];  
  147.         System.arraycopy(slackList, 0, list, 0, actualSize);  
  148.         return list;  
  149.     }  
  150. }            



0 0
原创粉丝点击