Chapter 11

Concurrency

This chapter covers some of the basics of working with concurrency, from creating your own threads to asking the JVM to create them for you.

This chapter also introduces the Akka framework. It is a relatively new approach to working with concurrent programming that focuses on creating and processing messages, and allows the framework to manage the processing in parallel.

Using Threads

How do you run code in parallel?

Java code is run in threads. When you start a simple application, such as a traditional Hello World application, the code is run in the main thread. As you would expect, an application needs at least one thread to run.

It is possible to create your own threads. Whenever you create a new thread, the code provided to run in that thread will run immediately. Considering that it is not physically possible to run more than one piece of code on a single CPU core at any one time, it is the job of the JVM to manage these threads and schedule which thread to run and when.

Listing 11-1 shows a very simple example of running code in a separate thread.

Listing 11-1: Running two blocks of code simultaneously

public class Threads { public static void main(String[] args) throws InterruptedException { final Thread separateThread = new Thread(new ThreadPrinter()); separateThread.start(); for(int i = 0; i < 5; i++) { System.out.println("From the main thread: " + Thread.currentThread().getName()); Thread.sleep(1000); } } } public class ThreadPrinter implements ...

Get Java Programming Interviews Exposed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.