java.lang.Thread.activeCount()方法实例

本文介绍Java中线程的创建及管理方法,重点讲解了如何使用java.lang.Thread.activeCount()方法来获取当前活动线程的数量,并给出了一个具体的示例程序。

java.lang.Thread.activeCount() 方法返回活动线程的当前线程的线程组中的数量。

 

例子

下面的例子显示java.lang.Thread.activeCount()方法的使用。

package com.bjsxt.demo;

public class ThreadDemo {

   public static void main(String[] args) {

     Thread t = Thread.currentThread();
     t.setName("Admin Thread");
     // set thread priority to 1
     t.setPriority(1);
     
     // prints the current thread
     System.out.println("Thread = " + t);
     //线程1
     Thread threadA = new Thread(new Runnable(){
		@Override
		public void run() {
              try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}		 	
		}
	 });
     
     //线程2
     Thread threadB = new Thread(new Runnable(){
 		@Override
 		public void run() {
               try {
 				Thread.sleep(3000);
 			} catch (InterruptedException e) {
 				e.printStackTrace();
 			}		 	
 		}
   	 });
     //给线程命名
     threadA.setName("Thread A");
     threadB.setName("Thread B");
     //启动线程
     threadA.start();
     threadB.start();
     
     int count = Thread.activeCount();
     System.out.println("currently active threads = " + count);
    
     Thread th[] = new Thread[count];
     // returns the number of threads put into the array 
     Thread.enumerate(th);
    
     // prints active threads
     for (int i = 0; i < count; i++) {
        System.out.println(i + ": " + th[i]);
     }
   }
} 

 输出结果如下:


说明:线程组(ThreadGroup)就是由线程组成的管理线程的类,这个类是java.lang.ThreadGroup类。

在Java中每一个线程都归属于某个线程组管理的一员,例如在主函数main()主工作流程中产生一个线程,则产生的线程属于main这个线程组管理的一员。

定义一个线程组,通过以下代码可以实现。
ThreadGroup group=new ThreadGroup("group");
Thread thread=new Thread(group,"the first thread of group");
ThreadGroup类中的某些方法,可以对线程组中的线程产生作用。例如,setMaxPriority()方法可以设定线程组中的所有线程拥有最大的优先权。
01-Jul-2025 18:26:22.896 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [/ecm-sf5-cn] startup failed due to previous errors 01-Jul-2025 18:26:22.968 WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [ecm-sf5-cn] appears to have started a thread named [Catalina-utility-2] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:4825) org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1172) org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1176) org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1176) org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1154) java.base@17.0.12/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) java.base@17.0.12/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) java.base@17.0.12/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) java.base@17.0.12/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) java.base@17.0.12/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63) java.base@17.0.12/java.lang.Thread.run(Thread.java:840) 01-Jul-2025 18:26:22.968 WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [ecm-sf5-cn] appears to have started a thread named [DefaultQuartzScheduler_QuartzSchedulerThread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: java.base@17.0.12/java.lang.Object.wait(Native Method) org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:427) 01-Jul-2025 18:26:22.977 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [ecm-sf5-cn] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@3777677a]) and a value of type [com.documentum.web.env.app.AppServerEnvironment] (value [[Name = App Server Environment, Description = App Server Environment Implementation, Major Version = 0, Minor Version = 1, Author = Documentum, Portal Description = App Server, Portal Version = x.x, Environment Base Version = 1.0, Environment Service Version = 6.0, Supports Dispatch Contract = true, Supports Theme Contract = true, Supports Error Contract = true, Supports FormOperationListener Contract = false, Supports Locale Contract = true, Supports Session Contract = true, Supports Tag Contract = false, Supports Render Contract = true, Supports Login Contract = false, Supports Security Contract = true, Supports ActionPrecondition Contract = false, Supports MessageService Contract = false, Supports SuperCredentials Contract = true, Supports Preference Contract = true, Supports ContentTransfer Contract = true]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak. [2025-07-01 06:26:22,998] Artifact ecm-sf5-cn: Error during artifact deployment. See server log for details.
07-02
08-Sep-2025 13:35:44.453 SEVERE [http-nio-8080-exec-15] org.apache.catalina.core.StandardContext.startInternal Context [/mesFERROTEC] startup failed due to previous errors 08-Sep-2025 13:35:44.976 WARNING [http-nio-8080-exec-15] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [mesFERROTEC] registered the JDBC driver [com.mysql.cj.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 08-Sep-2025 13:35:44.978 WARNING [http-nio-8080-exec-15] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [mesFERROTEC] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: java.lang.Object.wait(Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144) com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:85) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) java.lang.Thread.run(Thread.java:748) 08-Sep-2025 13:35:44.979 WARNING [http-nio-8080-exec-15] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [mesFERROTEC] appears to have started a thread named [pool-21-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215) java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078) java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093) java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) java.lang.Thread.run(Thread.java:748) 08-Sep-2025 13:35:44.986 INFO [http-nio-8080-exec-15] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/usr/local/tomcat/webapps/mesFERROTEC.war] has finished in [109,199] ms 08-Sep-2025 13:35:47.008 INFO [mysql-cj-abandoned-connection-cleanup] org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access. java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access. at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1378) at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1030) at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.checkThreadContextClassLoader(AbandonedConnectionCleanupThread.java:117) at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:84) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)
最新发布
09-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值