I’m programming on Android, but I guess this is a general Java 101 question…
I want myMethod() to run every X ms without blocking the UI – it should be possible to start and stop this thread. The value of X milliseconds will change whilst it’s being run. myMethod() needs read access to an array which is manipulated by the UI.
How can I do this? As the interval changes I can’t use schedule(); so is this a valid case for sleep(int X)? If I do start a new thread (runnable or extending Thread) in a new class, how can I read the UI class’s array? (does something like parent.getarray() exist?). What’s the best way to tackle this?
ScheduledThreadPoolExecutorclass gives you scheduling functionality. It has some advantages over java.util.TimerI don’t know Android, but it seems that ScheduledThreadPoolExecutor is available on Android as well.
Using STPE is simple: you create your
RunnableorCallableinstance, and pass it to your executor viaschedulemethod together with scheduling information (how often it is called, what is beginning delay).To access array from your UI thread, you need to use some kind of synchronization. Take a look at AtomicReferenceArray, AtomicLongArray or AtomicIntegerArray if they can help you (they give you atomic access to array elements without any other synchronization, although you better make your array variables final). Other option is to put all reads and writes to array into
synchronizedblocks. Another possibility is to use CopyOnWriteArrayList. If you need to also update UI from your background task, you need to wrap your updating code into another Runnable and pass it to UI thread. Best option really depends on what exactly you’re doing.