线程创建监听器

是否可以在java中编写线程创建监听器? 例如使用aop?!

我的意思是这样的,如果我的应用程序创建一个线程,我想在我自己的表,容器或其他东西中注册这个对象。

我认为这可能是AOP(例如aspectj)。 但是仍然需要创建自己的ThreadThreadGroup / Executor类型,除非您可以使用Aspect编译器重新编译JDK类。 如果要在线程启动时注册,或者如果要在创建线程对象时注册池中的createThread ,请在线程的start方法上定义切入点。


以下工作仅适用于使用aspect编译器重新编译JDK:所有线程都是使用Thread.start启动的,因此为该方法编写切入点然后您可以使用建议来执行您想要的操作。 当然这并不完美,因为例如cachedThreadPool执行器可能无法为每个任务启动一个新线程,但是如果你在Runnable.runCallable.call而不是Thread.start上注册一个切入点,那就足够了。

我会创建一个不断列出JVM上所有正在运行的线程的线程。
然后每当它出现新线程出现时,它都会以任何方式通知代码中的一个类。

以下是有关如何列出当前在JVM上运行的所有线程的一些链接:

  1. 获取当前在Java中运行的所有线程的列表

  2. 列出所有正在运行的线程

============

起始码:

ThreadCreationListener.java

 public interface ThreadCreationListener { public void onThreadCreation(Thread newThread); } 

ThreadCreationMonitor.java

 public class ThreadCreationMonitor extends Thread { private List listeners; private boolean canGo; public ThreadCreationMonitor() { listeners = new Vector();//Vector class is used because many threads may use a ThreadCreationMonitor instance. canGo = true; // Initialize the rest of the class here... } // Most important methods public void addListener(ThreadCreationListener tcl) { listeners.add(tcl); } public void removeListener(ThreadCreationListener tcl) { listeners.remove(tcl); } public void run() { List runningThreads; List lastRunningThreads; while(canGo) { // Step 1 - List all running threads (see previous links) // runningThreads = ... // Step 2 - Check for new threads and notify all listeners if necessary if (runningThreads.removeAll(lastRunningThreads)==true) { for(Thread t : runningThreads) { for(ThreadCreationListener tcl : listeners) { tcl.onThreadCreation(t);//Notify listener } } } } } public void shutdown() { canGo = false; } 

}

MyThreadInfoConsumer.java

 public class MyThreadInfoConsumer implements ThreadCreationListener { public void onThreadCreation(Thread newThread) { // Process here the notification... } } 

Main.java

 public class Main { public static void main(String[] args) { ThreadCreationMonitor tcm = new ThreadCreationMonitor(); tcm.start(); MyThreadInfoConsumer myTIC = new MyThreadInfoConsumer(); tcm.addListener(myTIC); // rest of your code... // Don't forget to call tcm.shutdown() when exiting your application ! } } 

也许ThreadGroup就是你所需要的。 所有线程都是ThreadGroup的成员,当您启动一个新线程时,它默认添加到与其父线程相同的组中。

理论上,当从组中添加或删除线程时,可能(但不推荐)子类被通知。

轮询这些组的线程或轮询所有线程可能是更好的解决方案。