Search code examples
javaandroidmultithreadingrunnable

What is the best way to pass data to a Runnable?


I generally write most of my code without worrying about threading and such, and get it working and debugged before trying to offload pieces to other threads. For me, the simplest way to do it is to break the function down into a Runnable or two. From there I can start a piece via new Thread(runnable).start() and other pieces I start on the main thread via handler.post().

The problem is that I can't pass arguments. I can sometimes get around this, but too often I end up using non-local variables, which makes things a real mess. Any ideas on the "correct" way to pass arguments to a runnable?


Solution

  • I usually create a new class implementing Runnable and pass arguments as constructor parameters and store them in final fields.

    If I need a result back from computation I implement Callable instead.

    I am also using executors rather than threads directly.