Java Programming Tutorials

Java programming tutorials with many code examples!

Java Runnable

Problem:

How to correctly run tasks that implement Java Runnable? In the following example we’re going to show how to use the most fundamental interface of Java concurrency.

Solution:

The simplest way to create a new task that can be run in a separate Thread is to implement java.lang.Runnable. It has only one method run() that has to be implemented by every Thread or Runnable task.

The following code creates a Counter that counts from zero to given number and shows what happens whet Runnable is called inappropriately:

package com.farenda.java.lang;

public class RunnableExample {

    private static class Counter implements Runnable {

        private final int number;

        public Counter(int number) {
            this.number = number;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println("Counter's thread: " + threadName);
            for (int i = 0; i < number; ++i) {
                System.out.println("counter's value: " + i);
            }
        }
    }

    public static void main(String[] args) {
        final String mainThreadName = Thread.currentThread().getName();
        System.out.println("Main thread: " + mainThreadName);

        Runnable counter = new Counter(2);

        System.out.println("\nRunning Runnable.run() without Thread:");
        counter.run();

        Thread counterThread = new Thread(counter, "counter-thread");
        System.out.println("\nRunning Thread.run() without starting the Thread:");
        counterThread.run();

        // Thread.start() will call Runnable.run()
        System.out.println("\nRunning using Thread.start():");
        counterThread.start();

        System.out.println("\nEnd of main()");
    }
}

Always there’s a Thread executing code. Even in a program where you don’t create threads there’s the main thread that runs the program. We use static method Thread.currentThread() to access name of Thread running current code. If it is called in the main thread then it returns it. If it is called withing code executed by some other thread, then that thread is returned. See program output and it will be immediately clear. ;-)

The result of running the above concurrent program:

Main thread: main

Running Runnable.run() without Thread:
Counter's thread: main
counter's value: 0
counter's value: 1

Running Thread.run() without starting the Thread:
Counter's thread: main
counter's value: 0
counter's value: 1

Running using Thread.start():

End of main()
Counter's thread: counter-thread
counter's value: 0
counter's value: 1

We print the thread’s name to show which thread currently executes that line of code. As you can see simply calling Runnable.run() doesn’t start a new thread and is just a simple method call – like it would be any other class. To execute that code in another thread we have to call start() method on Thread. It allocates resources for a new thread and executes Runnable.run() for us. Note that in the output after “Thread.start()” the thread’s name has changed to counter-thread.

Very important thing to note is that the new thread’s code can run in unpredictable order. Note that in the output “End of main()” appears before Counter’s output, which has been called sooner.

In the subsequent posts will dig into Java concurrency, so stay tuned. :-)

Share with the World!