File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes advice sampling thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "advice sampling thread" Watch "advice sampling thread" New topic

advice sampling thread

Karsten Daemen

Joined: Nov 19, 2009
Posts: 19

I'm currently working with some fellow students on a "school" project involving Lego Mindstorms. We're using Lejos to run java programs on the Lego robot.

Through Libraries we have an object 'sensor' that updates a variable every 20 ms. I can read this variable using the method 'readValue()'. I've written the following thread to sample this sensor at 20ms:

Our mentor however, isn't happy with the "Thread.sleep(20)" method we're using to achieve the sampling effect (because of the inaccuracy of the sleep method). He hinted that there was a better way to do this. Could you suggest some other better method or at least give me a hint in which direction to search? I'm very ill experienced in Threads.

Thanks in advance for your advice!
Tom Reilly

Joined: Jun 01, 2010
Posts: 618
How about using some kind of Timer or StopWatch class?

BTW, you should declare your finished variable as volatile.
Karsten Daemen

Joined: Nov 19, 2009
Posts: 19
Thanks I'll look in to that!

After I looked it up, 'finished' should be indeed volatile.
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

Given your mentor's concern over the accuracy of the sleep timer, I am not sure the Timer, or a stop watch would be any better. Does the leJos tutorial provide an alternate to polling?

[hint] yes ;-) [/hint]

Karsten Daemen

Joined: Nov 19, 2009
Posts: 19
Thanks Steve, that was exactly what I'm looking for! I was searching in the wrong direction, it has nothing to do with the threat architecture, just a simple Listener suffices.

Moral of this Topic:
Read the damn documentation!

Again thanks!
I agree. Here's the link:
subject: advice sampling thread
jQuery in Action, 3rd edition