In Java, threads can be grouped together and associated with an instance of threadgroup. in this chapter, I'll show you how to use some of the methods of threadgroup. at the end of the chapter, I'll show you how to use the class threadviewer to display the status of all the threads running in the Java VM.
Constructor:Threadgroup groupB = new threadgroup ("groupB"); threadgroup groupD = new threadgroup (groupc, "groupD"); // parent thread group
GetName ()To retrieve the name of a participant group, the getname () method is used. String groupname = group. getname (); returns the thread group name.
ThreadConstructorNew thread objects default to be in the same thread group as the thread that does the constructionthread threadz = new thread (target ); by default, the new thread is in the current thread group if a new thread should be in another group, and the desired thread group can be passed to the constructor for thread. thread threadz = new thread (groupc, target); you can also specify the thread group to which the thread belongs.
GetParent ()If you need to know which thread group A participant thread group belongs to, you can use the getparent () method on threadgroup.
Threadgroup parentofgroupd = groupD. getparent (); If getparent () is invoked on the Root thread group, null is returned. in the VM, only one instance of threadgroup does not have a parent group, and that is the root group. obtain the parent thread group of the thread group. If the root thread group calls this method, null is returned. Java Virtual Machine has only one root thread.
ActiveGroupCount ()/enumerate (ThreadGroup [])The activegroupcount () method returns the number of active thread groups in a participant threadgroup
And all of its subgroups. Keep in mind that this can be dynamically changing, but it's an accurate snapshot at a moment in time. returns the number of all active thread groups in the call thread group and its subthread group, which is only the value at a certain time point. To get a reference to all of the groups and subgroups of A threadgroup, The enumerate (threadgroup []) method can be used. if you don't want to include a recursive search of the subgroups, use enumerate (threadgroup [], false) instead. both methods return the number of groups copied into the array that is passed. if the array is not big enough, the extra groups are silently ignored. to get an idea How big the destination array needs to be, you can use the value returned from activegroupcount (). this code tries to capture all of the groups and subgroups of group: Enumerate (threadgroup []) returns all thread groups in this thread group, including the thread group enumerate (threadgroup [], false) in the sub-thread group to return all the thread groups in this thread group, two methods, excluding the thread group in the sub-thread group, return the thread group through the parameter. If the thread group given by the parameter is not large enough, ignore the remaining ones. Therefore, try to be as big as possible. The following code returns an array of all thread groups in the thread group. The actual size is threadgroup group Group = // ...int estimatedsize = 2 * group.
ActiveGroupCount(); Threadgroup [] DEST = new threadgroup [estimatedsize]; int actualsize = group.
Enumerate(DEST); the count returned from activegroupcount () is doubled in an attempt to be sure that the destination array is large enough. based on estimatedsize, a destination array for the groups is allocated and referred to by DeST. the enumerate (threadgroup []) method copies up to DeST. length groups into DeST. the number of groups copied is returned and stored in actualsize. if actualsize is equal to DeST. length, there is a good chance that DEST was not big enough. generally, actualsize is less than DeST. length and indicates the number of valid groups in DeST.
GetThreadGroup ()If you need to know which thread group a thread belongs to, you can use the getThreadGroup () method on Thread. threadGroup groupForThreadX = threadX. getThreadGroup (); groupForThreadX is a reference to the ThreadGroup that threadX belongs. if a thread is no longer alive, getThreadGroup () returns null instead of a ThreadGroup. to determine which thread group the thread executing a block of code belongs to, use: ThreadGroup group = Thread. currentThread (). getThreadGroup ();
ActiveCount ()The activeCount () method returns the number of active threads in a participant ThreadGroup
And all of its subgroups. Keep in mind that this can be dynamically changing, as new threads might be created and existing threads might be dying. to get a reference to all of the threads in a threadgroup and all of its subgroups, the enumerate (thread []) method can be used. if you don't want to include a recursive search of the subgroups, use enumerate (thread [], false) instead. both methods return the number of threads copied into the passed array. if the array is not big enough, the extra threads are silently ignored. to get an idea of how big the destination array needs to be, you can use the value returned from activecount (). this code tries to capture all of the threads in group and its subgroups: threadgroup group = // ...int estimatedsize = 2 * group.
ActiveCount(); Thread [] DEST = new thread [estimatedsize]; int actualsize = group.
Enumerate(DEST); Same as above, all threads in the thread group are returned.
CheckAccess ()The checkAccess () method of ThreadGroup is called internally by limit of the other ThreadGroup methods. it checks to see if a SecurityManager exists for a VM. by default, applications do not have a SecurityManager installed. applets, on the other hand, might ave one. if a SecurityManager exists and it determines that a participant thread is not permitted to take an action, it throws a securitypolicti On. securityException is a subclass of RuntimeException, so try/catch blocks are typically not used. if no SecurityManager is installed, or if the SecurityManager approves of the access, checkAccess () silently returns. check whether SecurityManager is included in the Virtual Machine. Generally, no SecurityManager exists, such as an Applet. If a thread does not allow access, this method throws a SecurityException. If no access is allowed or no access is allowed, the system returns the result directly.
SetMaxPriority ()/getMaxPriority ()The setMaxPriority () method sets the maximum priority that all threads in a participant thread group and all of its subgroups can have. threads that are already running at a higher priority are not affected. this method has an effect when new threads are constructed or when the setPriority () method of Thread is invoked. if setPriority () is called with a priority higher than the maximum allowed for t He group that a thread is in, the priority is silently lowered to the maximum allowed. the getMaxPriority () method returns the current maximum priority permitted for threads in a participant thread group. sets the maximum priority of all threads in the thread group (including threads in the sub-thread group. It does not affect existing threads with a higher priority. When the new thread is set with a higher priority, the priority will be directly reduced to the maximum priority of the thread group.
Interrupt ()The interrupt () method of ThreadGroup can be used to signal an interrupt to all the threads in the group and subgroups. this method can be useful if several threads have been spawned to handle a task, and it's time to signal all of them to shut down. (See Chapter 5, "Gracefully Stopping Threads," for more on signaling threads to die by interrupting them .) the interrupt () of the thread group terminates all threads in the thread group.
Deprecated --Stop (),Suspend (),Resume ()Class ThreadViewerThe class ThreadViewer (see Listing 10.1) graphically displays all of the threads currently running in the Java VM. it automatically refreshes itself every 5 seconds to keep current. threadViewer can be a handy tool to have around during the development and debugging of multithreaded applications. display All threads of the current Java Virtual Machine and their statuses in a chart. Refresh once in 5 seconds to keep updates.
ThreadViewerTableModel. java/** Created on 2005-7-18 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter9; import Java. AWT. *; import Java. lang. reflect. *; import javax. swing. *; import javax. swing. table. *;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** enjoy life with sun! **/Public class threadviewertablemodel extends acttablemodel {private object datalock; private int rowcount; private object [] [] celldata; private object [] [] pendingcelldata; /* column information */private final int columncount; private final string [] columnname; private final class [] columnclass;/* Self-running object and control variable */private thread internalthread; private volatile Boolean nostoprequested;/* constructor */Public thread Viewertablemodel () {rowcount = 0; celldata = new object [0] [0]; string [] names = {"Priority", "alive", "daemon ", "interrupted", "threadgroup", "thread name"}; columnname = names; class [] classes = {integer. class, Boolean. class, Boolean. class, Boolean. class, String. class, String. class}; columnclass = classes; columncount = columnname. length;/* control concurrent access */datalock = new object (); nostoprequested = true; runna Ble r = new runnable () {public void run () {try {runwork ();} catch (exception e) {e. printstacktrace () ;}}; internalthread = new thread (R, "threadviewer"); internalthread. setpriority (thread. max_priority-2); internalthread. setdaemon (true); // The daemon thread ends internalthread with the end of the main thread. start ();} private void runwork () {runnable transferpending = new runnable () {public void run () {transferpendingcelldata ();/ * Method of the abstracttablemodel class. Update table */firetabledatachanged () ;}}; while (nostoprequested) {try {creatependingcelldata (); swingutilities. invokeandwait (transferpending); thread. sleep (5000);} catch (invocationtargetexception E1) {e1.printstacktrace (); stoprequest ();} catch (interruptedexception E2) {thread. currentthread (). interrupt () ;}} private void creatependingcelldata () {thread [] thread = findallthr EADS (); object [] [] Cell = new object [thread. length] [columncount]; for (INT I = 0; I <thread. length; I ++) {thread t = thread [I]; object [] rowcell = cell [I]; 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 ();} synchr Onized (datalock) {pendingcelldata = cell;} Private Static thread [] findallthreads () {threadgroup group = thread. currentthread (). getthreadgroup (); threadgroup topgroup = group;/* Get the root thread group cyclically */while (group! = NULL) {topgroup = group; Group = group. getparent ();} int estimatedsize = topgroup. activecount () * 2; thread [] slacklist = new thread [estimatedsize]; int actualsize = topgroup. enumerate (slacklist);/* handcuff the list to the actual size */thread [] list = new thread [actualsize]; system. arraycopy (slacklist, 0, list, 0, actualsize); return list;} private void transferpendingcelldata () {synchronized (datalock) {celldata = pendingcelldata; rowcount = celldata. length ;}} public void stoprequest () {nostoprequested = false; internalthread. interrupt ();} public Boolean isalive () {return internalthread. isalive ();}/* (non-javadoc) * @ see javax. swing. table. tablemodel # getcolumncount () */Public int getcolumncount () {// todo auto-generated method stub return columncount;}/* (non-javadoc) * @ see javax. swing. table. tablemodel # getrowcount () */Public int getrowcount () {// todo auto-generated method stub return rowcount;}/* (non-javadoc) * @ see javax. swing. table. tablemodel # getvalueat (INT, INT) */public object getvalueat (INT rowindex, int columnindex) {// todo auto-generated method stub return celldata [rowindex] [columnindex];} public class getcolumnclass (INT columnindex) {return columnclass [columnindex];} Public String getcolumnname (INT columnindex) {return columnname [columnindex];}
ThreadViewer. java/** Created on 2005-7-18 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter9; import Java. AWT. *; import Java. AWT. event. *; import javax. swing. *; import javax. swing. table. *;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** enjoy life with sun! **/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 ();/* set the column width */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 static jframe createframedinstance () {final threadviewer viewer = new threadviewer (); Final jframe F = new jframe ("thread viewer"); F. addwindowlistener (New windowadapter () {public void windowclosing (invalid wevent e) {system. out. println ("windowclosing... "); F. setvisible (false); F. dispose (); viewer. dispose () ;}}); F. setcontentpane (viewer); F. setsize (500,300); F. setvisible (true); Return F;} public void dispose () {tablemodel. stoprequest ();} protected void finalize () throws throwable {dispose ();} public static void main (string [] ARGs) {jframe F = threadviewer. createframedinstance (); F. addwindowlistener (New windowadapter () {public void windowclosing (invalid wevent e) {system. out. println ("system. exit (0) "); system. exit (0) ;}}); object lock = new object (); synchronized (LOCK) {try {lock. wait () ;}catch (interruptedexception X ){}}}}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.