Threading Flashcards
What are the main ways to create threads?
- Extending the Thread class
- Implementing the Runnable interface
How we use Thread class?
Thread is a built-in class that can handle threading, imported through java.lang.Thread. The class that extends Thread will become threadable and can then override the built-in .run() method found in the parent class.
Using this approach also comes with the ability to .start() and .sleep() the created threads.
For example, let’s say we have a custom Factorial class that extends Thread. To use this class like a thread, we can do the following:
Factorial f = new Factorial(25); Factorial g = new Factorial(10); f.start(); g.start();
How we use Runnable interface?
This is often the preferred method over extending Thread because it allows you to extend other parent classes so long as you still include the necessary .run() method from Runnable. It’s also more intuitive to implement instead of extending because we’re not trying to extend the functionality of threads here, we’re just trying to use the functionality of threads.
Since the class itself is no longer technically a Thread, we can’t use .start() or other thread functionality on it like we can in the previous approach. However, when creating threads, we can actually pass an object of type Runnable to the Thread class which will then be used by that thread.
Doing this grants us access to all Thread functionality without extending from Thread because we’re simply using the actual Thread class itself.
For example, let’s say our previous custom Factorial class implements Runnable now. To use this new class like a thread, we can do the following:
Factorial f = new Factorial(25); Factorial g = new Factorial(10); Thread t1 = Thread(f); Thread t2 = Thread(g); t1.start(); t2.start();