Chapter 14. Concurrency
Threads in Java allow the use of multiple processors or multiple cores in one processor more efficiently. 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{publicvoidrun(){System.out.println("Orbiting");orbit();}}Comethalley=newComet();
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
interface and defining its run()
method can also create a threadable class. Creating a new Thread object and passing it an instance of
the runnable class creates the thread:
classAsteroidimplementsRunnable{publicvoidrun(){System.out.println("Orbiting");orbit();}}Asteroidmaja=newAsteroid();ThreadmajaThread=newThread(maja);
A single runnable instance can be passed to multiple thread objects. Each thread performs the same task:
Asteroidpallas=newAsteroid();ThreadpallasThread1=newThread(pallas);ThreadpallasThread2=newThread(pallas);
Thread States
Enumeration ...
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.
Read now
Unlock full access