Thread creation listener

前端 未结 3 551
灰色年华
灰色年华 2021-01-05 07:59

Is it possible to write Thread creation listener in java? For example using aop?!

I mean something like this that if my application creates a thread I would like to

3条回答
  •  粉色の甜心
    2021-01-05 08:09

    I would create a thread that continously lists all running threads on the JVM.
    Then each time it noticies that a new thread has appeared, it would notify in either way a class in your code.

    Here are some links about how to list all threads currently running on the JVM :

    1. Get a List of all Threads currently running in Java

    2. Listing All Running Threads

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

    A starting code :

    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 !
        }
    }
    

提交回复
热议问题