Problem:
How to create a task running as a Java Thread? Thread and Runnable are the most basic concurrent types to use. In this post we show how to use Thread to execute concurrent tasks.
Solution:
In the previous post you could learn how to correctly use Runnable interface. In this post we show how to create a task that directly extends from java.lang.Thread class and run two instances to do their jobs concurrently:
package com.farenda.java.lang; public class ThreadExample { private static class Counter extends Thread { // it's only to generate unique ids for each task: private static int threads = 0; private int id = ++threads; private final int number; public Counter(int number) { this.number = number; } @Override public void run() { for (int i = 0; i < number; ++i) { System.out.printf("counter %d, value: %d%n", id, i); } } } public static void main(String[] args) { Counter counter1 = new Counter(5); Counter counter2 = new Counter(5); System.out.println("Starting counters:"); counter1.start(); counter2.start(); System.out.println("main thread ends here"); } }
Whole task implementation is performed run() method. Note that threads are not started when instantiated, but only after call to start() method.
And here’s the output of the above program:
Starting counters: counter 1, value: 0 counter 1, value: 1 counter 1, value: 2 counter 2, value: 0 counter 2, value: 1 counter 2, value: 2 counter 2, value: 3 counter 2, value: 4 main thread ends here counter 1, value: 3 counter 1, value: 4
As you can see the execution of threads is non-deterministic and can occur in any order – here part of the first thread job has been executed after thread two.
Also note that the program finishes only when all the threads have finished the work.