Java - creating threads in a EventListener

╄→尐↘猪︶ㄣ 提交于 2019-12-11 10:15:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!