Vorrei creare un thread che elenchi continuamente tutti i thread in esecuzione sulla JVM.
Quindi ogni volta che notifica che un nuovo thread è apparso, notificherà in ogni modo una classe nel codice.
Ecco alcuni link su come elencare tutte le discussioni attualmente in esecuzione sulla JVM:
Get a List of all Threads currently running in Java
Listing All Running Threads
========= ===
un codice che inizia:
ThreadCreationListener.java
public interface ThreadCreationListener {
public void onThreadCreation(Thread newThread);
}
ThreadCreationMonitor.java
public class ThreadCreationMonitor extends Thread {
private List<ThreadCreationListener> listeners;
private boolean canGo;
public ThreadCreationMonitor() {
listeners = new Vector<ThreadCreationListener>();//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<Thread> runningThreads;
List<Thread> 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 !
}
}
Se si registra un 'ClassLoader' nel thread principale, si spera che sarà ereditato da tutti i nuovi thread e, si spera, qualsiasi thread dovrà caricare qualche classe, il che significa che il' ClassLoader' sarà consultato e si avrà un'opportunità per registrare il thread .... – Saintali
Vorrei seguire il percorso dell'estensione di 'Thread' con i metodi richiesti per gli ascoltatori. Certo, funzionerà solo per il tuo codice. – SJuan76
Devi seguire la transizione (come: "In questo momento è stata creata una nuova Discussione e devo reagire immediatamente") o è sufficiente avere una lista o qualcosa di thread creato nella/dalla tua applicazione a punti specifici nel tempo (come: "Ora voglio conoscere i thread e fare qualcosa con loro")? – Fildor