How to Add Buttons and Text to Your JavaFX Project
What Are Curly Braces in Java?
How to Use the javap Command

How to Use the Runnable Interface in Java to Create and Start a Thread

For the threads that trigger specific countdown events such as flooding the launch pad, starting the events, and lifting off, you can create another Java class called LaunchEvent. This class uses another technique for creating and starting threads — one that requires a few more lines of code but is more flexible.

The problem with creating a class that extends the Thread class is that a class can have one superclass. What if you’d rather have your thread object extend some other class? In that case, you can create a class that implements the Runnable interface rather than extends the Thread class.

The Runnable interface marks an object that can be run as a thread. It has only one method, run, that contains the code that’s executed in the thread. (The Thread class itself implements Runnable, which is why the Thread class has a run method.)

To use the Runnable interface to create and start a thread, you have to do the following:

  1. Create a class that implements Runnable.

  2. Provide a run method in the Runnable class.

  3. Create an instance of the Thread class and pass your Runnable object to its constructor as a parameter.

    A Thread object is created that can run your Runnable class.

  4. Call the Thread object’s start method.

    The run method of your Runnable object is called and executes in a separate thread.

The first two of these steps are easy. The trick is in the third and fourth steps, because you can complete them in several ways. Here’s one way, assuming that your Runnable class is named RunnableClass:

RunnableClass rc = new RunnableClass();
Thread t = new Thread(rc);
t.start();

Java programmers like to be as concise as possible, so you often see this code compressed to something more like

Thread t = new Thread(new RunnableClass());
t.start();

or even just this:

new Thread(new RunnableClass()).start();

This single-line version works — provided that you don’t need to access the thread object later in the program.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Searching for Text in Eclipse
5 Responsibilities of the Enterprise JavaBean Container
How to Use Blocks in Java
JavaFX: How to Combine Effects
Singling Out Stateless Session Beans in Enterprise JavaBeans
Advertisement

Inside Dummies.com