Threads
As we have mentioned already, the main application thread can create other - child - threads and let them run in parallel, either sharing the same core via time slicing or having a dedicated CPU for each thread. It can be done using the class java.lang.Thread
, which implements the functional interface Runnable
. The interface is called functional if it has only one abstract method (we will discuss functional interfaces in Chapter 17, Lambda Expressions and Functional Programming). The Runnable
interface contains one method, run()
.
There are two ways to create a new thread:
- Extend the
Thread
class - Implement the
Runnable
interface and pass the object of the implementation into the constructor of the classThread
Extending the Thread class
Whatever method is used, we end up with a Thread
class object that has the method start()
. This method call starts the thread execution. Let's look at an example. Let's create a class called AThread
that extends Thread
and overrides its run()
method:
public...