问题
I got this code:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
OctopusWSClient.sendPoolSensorReading(poolSensorReading, OctopusClientStart.currentMacAddress);
}
});
thread.setName("Thread - WS");
thread.start();
Is inside a Event Listener that is executing approximately every 30 seconds (When an event occurs), so is creating a new Thread every 30 seconds that usually last 20 seconds to complete, now, my question is... Its OK to call Threads this way?, if not, how???... and also, I'm watching Threads ID and names with this code:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for(Thread t : threadSet){
System.out.println(" Thread #"+t.getId()+" Name: "+t.getName());
}
and it prints the ID and name for the current threads, I see always the same number of Threads, but the ID is always incrementing by 1 (Thread - WS).
Is this a bad signal? It will fill JVM Memory in some time?
thanks
回答1:
You would probably find it better to notify a single thread to resume, rather than create multiple ones. If it takes 20 seconds to complete, at the end lock it and make it wait till it gets the command to restart the loop from the event listener.
来源:https://stackoverflow.com/questions/14737541/java-creating-threads-in-a-eventlistener