Skip to Content
Java Pocket Guide, 4th Edition
book

Java Pocket Guide, 4th Edition

by Robert Liguori, Patricia Liguori
August 2017
Intermediate to advanced
290 pages
4h 10m
English
O'Reilly Media, Inc.
Content preview from Java Pocket Guide, 4th Edition

Chapter 14. Concurrency

Threads in Java allow the use of multiple processors or multiple cores in one processor to be more efficient. On a single processor, threads provide for concurrent operations such as overlapping I/O with processing.

Java supports multithreaded programming features with the Thread class and the Runnable interface.

Creating Threads

Threads can be created two ways, either by extending java.lang.Thread or by implementing java.lang.Runnable.

Extending the Thread Class

Extending the Thread class and overriding the run() method can create a threadable class. This is an easy way to start a thread:

class Comet extends Thread {
  public void orbit() {
    System.out.println("orbiting");
  }
  public void run() {
    orbit();
  }
}

Comet halley = new Comet();
halley.start();

Remember that only one superclass can be extended, so a class that extends Thread cannot extend any other superclass.

Implementing the Runnable Interface

Implementing the Runnable functional interface and defining its run() method can also create a threadable class:

class Asteroid implements Runnable {
  public void orbit() {
    System.out.println("orbiting");
  }
  public void run() {
    orbit();
  }
}

Asteroid majaAsteroid = new Asteroid();
Thread majaThread = new Thread(majaAsteroid);
majaThread.start();

A single runnable instance can be passed to multiple thread objects. Each thread performs the same task, as shown here after the use of a lambda expression:

Runnable asteroid = () -> {
  System.out.println("orbiting" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java 8 Pocket Guide

Java 8 Pocket Guide

Robert Liguori, Patricia Liguori
Java 11 Cookbook - Second Edition

Java 11 Cookbook - Second Edition

Nick Samoylov, Mohamed Sanaulla

Publisher Resources

ISBN: 9781491938683Errata Page