Java-在EventListener中创建线程 [英] Java - creating threads in a EventListener

查看:446
本文介绍了Java-在EventListener中创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下代码:

Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OctopusWSClient.sendPoolSensorReading(poolSensorReading, OctopusClientStart.currentMacAddress);
                    }
                });
                thread.setName("Thread - WS");
                thread.start();

位于大约每30秒执行一次(事件发生时)的事件监听器中,因此每30秒创建一个通常持续20秒才能完成的新线程,现在,我的问题是...以这种方式调用线程?,如果不是,该如何使用?……而且,我正在用以下代码监视线程ID和名称:

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());
                }

它显示当前线程的ID和名称,我看到的线程数始终相同,但是ID总是递增1(线程-WS).

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).

这是一个不好的信号吗?它会在一段时间内填满JVM内存吗?

Is this a bad signal? It will fill JVM Memory in some time?

谢谢

推荐答案

您可能会发现通知单个线程继续运行比创建多个线程更好.如果需要20秒才能完成,请在最后将其锁定,并使其等待直到获得命令以从事件侦听器重新启动循环为止.

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.

这篇关于Java-在EventListener中创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆