不断检查端口而不使用 while 循环
在一个程序(Java)中,我需要检查并行端口中的特定引脚。每当该引脚从逻辑 0 变为 1(上升沿时钟)时,我必须读取端口上的数据并保存它。这种情况大约每 10 毫秒发生一次,但可能会略有不同。
为此,我创建了一个带有 while 循环的单独线程,该循环不断检查端口,但这会使处理器发疯,我知道这是因为 while 循环。我的问题是,如何在不使用处理器密集型 while 循环的情况下不断扫描端口?该程序并不确切知道引脚变化何时发生,只知道它大约每 10 毫秒发生一次。
In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.
To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
触发一个线程,该线程计划以固定速率执行给定的 Runnable 。您可以使用
Timer#scheduleAtFixedRate()
或ScheduledExecutorService#scheduleAtFixedRate( )
为此。最后一个是首选。其中
PortScanner
看起来像这样:不要忘记在应用程序退出时调用
scheduler.shutdown()
,否则线程可能会挂起。Fire a thread which is scheduled to execute the given
Runnable
at a fixed rate. You can useTimer#scheduleAtFixedRate()
orScheduledExecutorService#scheduleAtFixedRate()
for this. The last one is preferred.Where
PortScanner
can look like this:Don't forget to call
scheduler.shutdown()
at the moment your application exits, else the thread may hang.可能有更好的解决方案,但最坏的情况下,每次 while 循环迭代时,您都可以使用
Thread.sleep
1-2ms。There might be a better solution, but worst case you could just
Thread.sleep
for 1-2ms every iteration of the while loop.当您的代码没有作为操作系统的一部分运行时,捕获硬件中断确实很棘手。你能做的就是放置 Thread.Sleep ( 5 )。这将休眠 10 毫秒,并让其他线程运行或只是保持 CPU 空闲和冷却。 5 毫秒的延迟应该足以确保不会错过任何时钟滴答声。
当您的时钟在 10 毫秒高和 10 毫秒低之间交替时,这将起作用。对于其他模式,您必须相应地调整参数。
It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.
This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.