====== Basics ======
* Thread should be seen as **deprecated**
====== Executor Framework ======
Java introduces the [[http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html|Executor Framework]] as a new Highlevel Mechanism to handle concurrency.
Basically this includes the following steps:
* Create a Worker classes that either implements Runnable or Callable
* Create Worker instances
* Create an ExecutorService
* newSingleThreadExecutor
* newCachedThreadPool
* newFixedThreadPool
* Submit the workers to the executor service
* Wait for the workers to finish
* Shutdown the ExecutorService
===== Example: Thread Pool =====
public class ThreadPoolExecutorDemo {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new Worker());
executor.submit(new Worker());
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS); // wait until finished, but at most for 60 seconds
System.out.println("Done");
}
public static class Worker implements Runnable {
@Override
public void run() {
// do work
}
}
}
If the Worker should yield a result, implement **Callable** instead of Runnable:
public class ThreadPoolTest {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future result1 = executor.submit(new Worker());
Future result2 = executor.submit(new Worker());
System.out.println("Results: " + result1.get() + " " result2.get()); // note that get() might throw an Exception if the worker did not finish normally
}
public static class Worker implements Callable {
@Override
public Integer call() {
int result=0;
// do some work
return result;
}
}
}
===== Waiting until tasks are done =====
public static void main(String[] args) throws Exception {
List tasks = new ArrayList<>();
tasks.add(new Worker());
tasks.add(new Worker());
ExecutorService executor = Executors.newFixedThreadPool(2);
List> results = executor.invokeAll(tasks); // blocks until all tasks are done
System.out.println("Result1: " + results.get(0).get());
System.out.println("Result2: " + results.get(1).get());
System.out.println("Done");
executor.shutdown();
}
public static class Worker implements Callable {
.....
}