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:
classCometextendsThread{publicvoidorbit(){System.out.println("orbiting");}publicvoidrun(){orbit();}}Comethalley=newComet();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:
classAsteroidimplementsRunnable{publicvoidorbit(){System.out.println("orbiting");}publicvoidrun(){orbit();}}AsteroidmajaAsteroid=newAsteroid();ThreadmajaThread=newThread(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:
Runnableasteroid=()->{System.out.println("orbiting" ...