Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Runnable

farenda 2015-09-29 0

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!
Categories Java Tags java, java-concurrency
Previous: Java Calendar
Next: Java Thread example

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored