| Free tutorials for Java, Eclipse and Web programming |
The base means for concurrency are java.lang.Threads. Each thread requires a java.lang.Runnable which contains in the method run the unit of work which must be performed.
Think of runnable as the task to perform. The thread is the worker who is doing this task.
For example this is a simple task (Runnable) which counts the sum of a given range of numbers.
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 these tasks (Runnables) you need threads. The following will create threads, assign runnable to these threads and wait until they 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);
}
}
Threads were the first approach in Java to support concurrency. The usage of the threads 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.