Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

5. 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;
	}

	@Override
	public void run() {
		long sum = 0;
		for (long i = 1; i < countUntil; i++) {
			sum += i;
		}
		System.out.println(sum);
	}
}

		

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
			worker.setName(String.valueOf(i));
			// Start the thread, never call method run() direct
			worker.start();
			// Remember the thread for later usage
			threads.add(worker);
		}
		int running = 0;
		do {
			running = 0;
			for (Thread thread : threads) {
				if (thread.isAlive()) {
					running++;
				}
			}
			System.out.println("We have " + running + " running threads. ");
		} while (running > 0);

	}
}

		

Using Threads directly has the following disadvantages.

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.