Posted in Uncategorized

Threads in Java

The base means for concurrency are “java.lang.Threads”. Each thread will execute an object of type “java.lang.Runnable”. Runnable is an interface with defines only the one method “run()”. This method is called by “Thread” and contains the work which should be done. Therefore the “Runnable” is the task to perform. The Thread is the worker who is doing this task.
The following demonstrates a task (Runnable) which counts the sum of a given range of numbers. Create the Java project “de.vogella.concurrency.threads” for the example coding of this section.

package de.vogella.concurrency.threads;

* MyRunnable will count the sum of the number from 1 to the parameter
* countUntil and then write the result to the console.
* <p>
* MyRunnable is the task which will be performed
* @author Lars Vogel

public class MyRunnable implements Runnable {
private final long countUntil;

MyRunnable(long countUntil) {
this.countUntil = countUntil;

public void run() {
long sum = 0;
for (long i = 1; i < countUntil; i++) {
sum += i;

To perform a task (Runnables) you need to define and start a Thread. The following coding will create Threads, assigns a Runnable to each Thread, schedule the Threads to run and wait until all Threads are finished.

package de.vogella.concurrency.threads;

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {
// We will store the threads so that we can check if they are done
List<Thread> threads = new ArrayList<Thread>();
// We will create 500 threads
for (int i = 0; i < 500; i++) {
Runnable task = new MyRunnable(10000000L + i);
Thread worker = new Thread(task);
// We can set the name of the thread
// Start the thread, never call method run() direct
// Remember the thread for later usage
int running = 0;
do {
running = 0;
for (Thread thread : threads) {
if (thread.isAlive()) {
System.out.println("We have " + running + " running threads. ");
} while (running > 0);


Using Threads directly has the following disadvantages.

  • Creating a new thread causes some performance overhead
  • Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
  • You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.

The “java.util.concurrent” package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the issues with threads.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s