`
aerchi
  • 浏览: 427280 次
  • 性别: Icon_minigender_1
  • 来自: 昆明
文章分类
社区版块
存档分类
最新评论

Java 多线程编程之四:获取 Java VM 中当前运行的所有线程

阅读更多

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

程序运行图:

程序运行效果图
下面的静态方法可以用数组返回 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 源代码:

  1. packagethread;
  2. importjava.awt.*;
  3. importjava.awt.event.*;
  4. importjavax.swing.*;
  5. importjavax.swing.table.*;
  6. publicclassThreadViewerextendsJPanel{
  7. privateThreadViewerTableModeltableModel;
  8. publicThreadViewer(){
  9. tableModel=newThreadViewerTableModel();
  10. JTabletable=newJTable(tableModel);
  11. table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
  12. TableColumnModelcolModel=table.getColumnModel();
  13. intnumColumns=colModel.getColumnCount();
  14. //manuallysizeallbutthelastcolumn
  15. for(inti=0;i<numColumns-1;i++){
  16. TableColumncol=colModel.getColumn(i);
  17. col.sizeWidthToFit();
  18. col.setPreferredWidth(col.getWidth()+5);
  19. col.setMaxWidth(col.getWidth()+5);
  20. }
  21. JScrollPanesp=newJScrollPane(table);
  22. setLayout(newBorderLayout());
  23. add(sp,BorderLayout.CENTER);
  24. }
  25. publicvoiddispose(){
  26. tableModel.stopRequest();
  27. }
  28. protectedvoidfinalize()throwsThrowable{
  29. dispose();
  30. }
  31. publicstaticJFramecreateFramedInstance(){
  32. finalThreadViewerviewer=newThreadViewer();
  33. finalJFramef=newJFrame("ThreadViewer");
  34. f.addWindowListener(newWindowAdapter(){
  35. publicvoidwindowClosing(WindowEvente){
  36. f.setVisible(false);
  37. f.dispose();
  38. viewer.dispose();
  39. }
  40. });
  41. f.setContentPane(viewer);
  42. f.setSize(500,300);
  43. f.setVisible(true);
  44. returnf;
  45. }
  46. publicstaticvoidmain(String[]args){
  47. JFramef=ThreadViewer.createFramedInstance();
  48. //Forthisexample,exittheVMwhentheviewer
  49. //frameisclosed.
  50. f.addWindowListener(newWindowAdapter(){
  51. publicvoidwindowClosing(WindowEvente){
  52. System.exit(0);
  53. }
  54. });
  55. //Keepthemainthreadfromexitingbyblocking
  56. //onwait()foranotificationthatnevercomes.
  57. Objectlock=newObject();
  58. synchronized(lock){
  59. try{
  60. lock.wait();
  61. }catch(InterruptedExceptionx){
  62. }
  63. }
  64. }
  65. }

程序 ThreadViewerTableModel.java 源代码:

  1. packagethread;
  2. importjava.awt.*;
  3. importjava.lang.reflect.*;
  4. importjavax.swing.*;
  5. importjavax.swing.table.*;
  6. publicclassThreadViewerTableModelextendsAbstractTableModel{
  7. privateObjectdataLock;
  8. privateintrowCount;
  9. privateObject[][]cellData;
  10. privateObject[][]pendingCellData;
  11. //thecolumninformationremainsconstant
  12. privatefinalintcolumnCount;
  13. privatefinalString[]columnName;
  14. privatefinalClass[]columnClass;
  15. //self-runningobjectcontrolvariables
  16. privateThreadinternalThread;
  17. privatevolatilebooleannoStopRequested;
  18. publicThreadViewerTableModel(){
  19. rowCount=0;
  20. cellData=newObject[0][0];
  21. //JTableusesthisinformationforthecolumnheaders
  22. String[]names={
  23. "Priority","Alive",
  24. "Daemon","Interrupted",
  25. "ThreadGroup","ThreadName"};
  26. columnName=names;
  27. //JTableusesthisinformationforcellrendering
  28. Class[]classes={
  29. Integer.class,Boolean.class,
  30. Boolean.class,Boolean.class,
  31. String.class,String.class};
  32. columnClass=classes;
  33. columnCount=columnName.length;
  34. //usedtocontrolconcurrentaccess
  35. dataLock=newObject();
  36. noStopRequested=true;
  37. Runnabler=newRunnable(){
  38. publicvoidrun(){
  39. try{
  40. runWork();
  41. }catch(Exceptionx){
  42. //incaseANYexceptionslipsthrough
  43. x.printStackTrace();
  44. }
  45. }
  46. };
  47. internalThread=newThread(r,"ThreadViewer");
  48. internalThread.setPriority(Thread.MAX_PRIORITY-2);
  49. internalThread.setDaemon(true);
  50. internalThread.start();
  51. }
  52. privatevoidrunWork(){
  53. //Therun()methodoftransferPendingiscalledby
  54. //theeventhandlingthreadforsafeconcurrency.
  55. RunnabletransferPending=newRunnable(){
  56. publicvoidrun(){
  57. transferPendingCellData();
  58. //MethodofAbstractTableModelthat
  59. //causesthetabletobeupdated.
  60. fireTableDataChanged();
  61. }
  62. };
  63. while(noStopRequested){
  64. try{
  65. createPendingCellData();
  66. SwingUtilities.invokeAndWait(transferPending);
  67. Thread.sleep(2000);
  68. }catch(InvocationTargetExceptiontx){
  69. tx.printStackTrace();
  70. stopRequest();
  71. }catch(InterruptedExceptionx){
  72. Thread.currentThread().interrupt();
  73. }
  74. }
  75. }
  76. publicvoidstopRequest(){
  77. noStopRequested=false;
  78. internalThread.interrupt();
  79. }
  80. publicbooleanisAlive(){
  81. returninternalThread.isAlive();
  82. }
  83. privatevoidcreatePendingCellData(){
  84. //thismethodiscalledbytheinternalthread
  85. Thread[]thread=findAllThreads();
  86. Object[][]cell=newObject[thread.length][columnCount];
  87. for(inti=0;i<thread.length;i++){
  88. Threadt=thread[i];
  89. Object[]rowCell=cell[i];
  90. rowCell[0]=newInteger(t.getPriority());
  91. rowCell[1]=newBoolean(t.isAlive());
  92. rowCell[2]=newBoolean(t.isDaemon());
  93. rowCell[3]=newBoolean(t.isInterrupted());
  94. rowCell[4]=t.getThreadGroup().getName();
  95. rowCell[5]=t.getName();
  96. }
  97. synchronized(dataLock){
  98. pendingCellData=cell;
  99. }
  100. }
  101. privatevoidtransferPendingCellData(){
  102. //thismethodiscalledbytheeventthread
  103. synchronized(dataLock){
  104. cellData=pendingCellData;
  105. rowCount=cellData.length;
  106. }
  107. }
  108. publicintgetRowCount(){
  109. //thismethodiscalledbytheeventthread
  110. returnrowCount;
  111. }
  112. publicObjectgetValueAt(introw,intcol){
  113. //thismethodiscalledbytheeventthread
  114. returncellData[row][col];
  115. }
  116. publicintgetColumnCount(){
  117. returncolumnCount;
  118. }
  119. publicClassgetColumnClass(intcolumnIdx){
  120. returncolumnClass[columnIdx];
  121. }
  122. publicStringgetColumnName(intcolumnIdx){
  123. returncolumnName[columnIdx];
  124. }
  125. publicstaticThread[]findAllThreads(){
  126. ThreadGroupgroup=
  127. Thread.currentThread().getThreadGroup();
  128. ThreadGrouptopGroup=group;
  129. //traversetheThreadGrouptreetothetop
  130. while(group!=null){
  131. topGroup=group;
  132. group=group.getParent();
  133. }
  134. //Createadestinationarraythatisabout
  135. //twiceasbigasneededtobeveryconfident
  136. //thatnoneareclipped.
  137. intestimatedSize=topGroup.activeCount()*2;
  138. Thread[]slackList=newThread[estimatedSize];
  139. //Loadthethreadreferencesintotheoversized
  140. //array.Theactualnumberofthreadsloaded
  141. //isreturned.
  142. intactualSize=topGroup.enumerate(slackList);
  143. //copyintoalistthatistheexactsize
  144. Thread[]list=newThread[actualSize];
  145. System.arraycopy(slackList,0,list,0,actualSize);
  146. returnlist;
  147. }
  148. }

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics