Summary
In this chapter, we have presented the most basic elements to create execution threads in Java: the Runnable interface and the Thread class. We can create threads in Java in two different ways:
- Extending the
Threadclass and overriding therun()method - Implementing the
Runnableinterface and passing an object of that class to the constructor of theThreadclass
The second mechanism is preferred over the first one because they give us more flexibility.
We also learned how the Thread class has different methods that allow us to get information about the thread, change its priority, or wait for its finalization. We have used all these methods in two examples, one to multiply matrices and the other to search files in a directory. In both cases, concurrency gives us better performance but we also have learned that we have to be careful when implementing a concurrent version of an algorithm. A bad selection for how we use concurrency can give us bad performance.
In the next chapter, we will...