线程和线程组(0分)

  • 主题发起人 主题发起人 chenzhongshan
  • 开始时间 开始时间
C

chenzhongshan

Unregistered / Unconfirmed
GUEST, unregistred user!
每一个java的Thread都属于某个ThreadGroup,并且能够通过该ThreadGroup的方法来限制和控制它
每一个ThreadGroup都包含于某个父亲ThreadGroup,这样,就有一个层次结构。下面的这个例子
定义是使用TextArea显示每一个线程的名称,优先权,以及其他关于线程和线程组的信息。
这样可以帮助你使用线程编程所遇到的困难。
=========================================================================================
package com.davidflanagan.example.thread;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2002
* Company:
* @author
* @version 1.0
*/
public class ThreadLister {
private static void printThreadInfo(PrintWriter out,Thread t,String indent){
if(t == null) return;
out.println(indent + "Thread :" + t.getName() + "Prority" + t.getPriority() +
(t.isDaemon()?"Demon":"") + (t.isAlive()?"":"Not Alive"));
}
/**
* 显示线程组信息
*/
private static void printThreadGroupInfo(PrintWriter out,ThreadGroup g,String indent){
if(g == null) return;
int numThreads = g.activeCount();
int numGroups = g.activeGroupCount();
Thread[] threads = new Thread[numThreads];
ThreadGroup[] threadGroups = new ThreadGroup[numGroups];
g.enumerate(threads,false);
g.enumerate(threadGroups,false);
out.println(indent + "Thread Group:" + g.getName() + "Max Priority:" + g.getMaxPriority() +
(g.isDaemon()?"Demon":""));
for(int i=0;i<numThreads;i++)
printThreadInfo(out,threads,indent + " ");
for(int i=0;i<numGroups;i++){
printThreadGroupInfo(out,threadGroups,indent + " ");
}
}
public static void listAllThreads(PrintWriter out){
ThreadGroup currentThreadGroup;
ThreadGroup rootThreadGroup;
ThreadGroup parent;
currentThreadGroup = Thread.currentThread().getThreadGroup();
rootThreadGroup = currentThreadGroup;
parent = rootThreadGroup.getParent();
while(parent != null){
rootThreadGroup = parent;
parent = rootThreadGroup.getParent();
}
printThreadGroupInfo(out,rootThreadGroup," ");
}
public static void main(String args[]){
javax.swing.JFrame frame = new javax.swing.JFrame("Test ThreadGroup");
javax.swing.JTextArea textArea = new javax.swing.JTextArea();
frame.getContentPane().add(new javax.swing.JScrollPane(textArea),java.awt.BorderLayout.CENTER);
frame.setSize(400,300);
frame.setVisible(true);
java.io.StringWriter sout = new StringWriter();
java.io.PrintWriter out = new PrintWriter(sout);
ThreadLister.listAllThreads(out);
out.close();
String threadListing = sout.toString();
textArea.setText(threadListing);
}
}
==============================================================================
我想在天空写下你的名字
却被风吹走了
我想在沙滩写下你的名字
却被海浪冲走了
我想在墙上写下你的名字
我靠
我被警察带走了
================================================================================
 
接受答案了.
 

Similar threads

后退
顶部