【Java】 获取当前项目所有的线程
生活随笔
收集整理的這篇文章主要介紹了
【Java】 获取当前项目所有的线程
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
jdk 1.8
獲取當前項目所有的線程
代碼
import java.util.Random;public class Test {public static void main(String[] args) {Test t = new Test();t.initThreadContext();try {Thread.sleep(5 * 1000);} catch (InterruptedException e) {}t.printAllThread();}public void printAllThread(){// 遍歷線程組樹,獲取根線程組ThreadGroup topGroup =Thread.currentThread().getThreadGroup();while (topGroup.getParent()!=null){// 返回此線程組的父線程組topGroup=topGroup.getParent();}// 線程數(shù)組大小為當前活動線程數(shù)量的2倍。Thread[] tmpThreadList = new Thread[topGroup.activeCount() * 2];// 獲取根線程組下的所有線程 int actualSize = topGroup.enumerate(tmpThreadList); // 拷貝到一個新的數(shù)組,數(shù)組長度為實際長度Thread[] threadList = new Thread[actualSize]; System.arraycopy(tmpThreadList, 0, threadList, 0, actualSize); // 打印for (Thread thread : threadList) {System.out.println(" 線程id:" + thread.getId() + " 線程名稱:" + thread.getName() + " 線程狀態(tài):" + thread.getState());}}public void initThreadContext() {for (int i=0; i<10; i++) {Thread t = new Thread() {public void run() {Random random = new Random();int times = random.nextInt(10) + 1;System.out.println("thread " + this.getId() + " started, run " + times + " seconds");for (int i=0; i<times; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {}}System.out.println("thread " + this.getId() + " done");}};t.start();}} }執(zhí)行結(jié)果
thread 10 started, run 8 seconds thread 12 started, run 1 seconds thread 11 started, run 3 seconds thread 13 started, run 6 seconds thread 14 started, run 1 seconds thread 15 started, run 7 seconds thread 17 started, run 7 seconds thread 16 started, run 2 seconds thread 18 started, run 2 seconds thread 19 started, run 3 seconds thread 12 done thread 14 done thread 18 done thread 16 done thread 19 done thread 11 done 線程id:2 線程名稱:Reference Handler 線程狀態(tài):WAITING 線程id:3 線程名稱:Finalizer 線程狀態(tài):WAITING 線程id:4 線程名稱:Signal Dispatcher 線程狀態(tài):RUNNABLE 線程id:5 線程名稱:Attach Listener 線程狀態(tài):RUNNABLE 線程id:1 線程名稱:main 線程狀態(tài):RUNNABLE 線程id:10 線程名稱:Thread-0 線程狀態(tài):TIMED_WAITING 線程id:13 線程名稱:Thread-3 線程狀態(tài):TIMED_WAITING 線程id:15 線程名稱:Thread-5 線程狀態(tài):TIMED_WAITING 線程id:17 線程名稱:Thread-7 線程狀態(tài):TIMED_WAITING thread 13 done thread 15 done thread 17 done thread 10 done總結(jié)
以上是生活随笔為你收集整理的【Java】 获取当前项目所有的线程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鼠标光标大改造如何加大鼠标光标
- 下一篇: Linux hwclock显示与设定硬件