O'Reilly logo

Java Programming Interviews Exposed by Noel Markham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required