📄 handlerthread.java
字号:
public class HandlerThread extends Thread{ // The default constructor for the HandlerThread public HandlerThread( ThreadGroup ownerGroup, String threadName ) { super( ownerGroup, threadName ); } // Override the parents run to do something different public void run() { // How many worker treads to start up int numberOfChildren = 3; // Declare the reference outside of the loop for better performance WorkerThread childThread = null; // Loop through and start up the worker threads for( int i = 1; i <= numberOfChildren; i++ ) { childThread = new WorkerThread( getThreadGroup(), "Thread" + String.valueOf(i) ); childThread.start(); } // Go to sleep for 3 seconds and let the worker threads so something try { sleep( 3000 ); } catch( InterruptedException ex ) { /* Don't need to handle this for now */ } // Get the thread group that I belong to ThreadGroup myGroup = getThreadGroup(); // how many active threads are in my group that I need to stop int activeEstimatedThreadCount = myGroup.activeCount(); Thread[] activeThreads = new Thread[ activeEstimatedThreadCount ]; // Get the count of active threads int activeThreadCount = myGroup.enumerate( activeThreads ); // Declare the refererence outside of the loop for performance Thread thread = null; // Loop through all of the active threads and signal them to quit for( int counter = 0; counter < activeThreadCount; counter++ ) { // Get one of the active threads out of the array thread = activeThreads[counter]; // Make sure it's a worker thread. There may be others active // If it is a worker thread, tell it to stop running if ( thread instanceof WorkerThread ) ((WorkerThread)thread).setKeepRunning(false); } } public static void main( String args[] ) { // Create a new ThreadGroup ThreadGroup threadGroup = new ThreadGroup( "MyNewGroup" ); // Start the handler which will start the worker threads HandlerThread handler = new HandlerThread( threadGroup, "HandlerThread" ); // Start the handler thread running handler.start(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -