This is an old revision of the document!
Runnables and you
There's nothing special about a Runnable. It's doesn't have anything to do with threads. All it is is an interface, that's it:
public class MyRunnable implements Runnable { public void run(){ System.out.println("MyRunnable running"); } }
The interface takes no parameters and returns no parameters.
You can create a runnable so you have something to send on a separate thread. You don't need a runnable to do it, it's just standard convention everybody seems to have agreed upon. Here's a nice friendly runnable to play with:
public class MyRunnable implements Runnable { public void run(){ Log.v("test","MyRunnable running"); } }
3 ways to create an instance of this runnable:
- Define the class as above and create an instance:
Runnable myRunnable = new MyRunnable
- Skip naming the class but still define it:
Runnable myRunnable = new Runnable(){ public void run(){ Log.v("Runnable running"); } }
- do “the lambda”:
Runnable myRunnable = () -> { Log.v("Lambda Runnable running"); };
Once you have a runnable or really any function wrapped up all pretty like this you can create a new thread to run it:
Thread thread = new Thread(myRunnable); thread.start();
Borrowed and reworded from here.