Java Threads


  • What Is a Thread?
  • Creating and Running Threads in Java
  • Synchronization
  • Using wait() and notify()
  • The Java Event Model
  • When to Use Threads
  • When Not to Use Threads
  • Sum It Up: Thread Pools
  • Summary

It's lunchtime, and you decide to treat yourself to a meal at your favorite restaurant. You take a seat and look around—the place is pretty empty. There's one waiter, one customer eating, and you. The waiter is helping the other customer, but oddly, you're being ignored. Even when you ask for a menu, the waiter acts as if you're not there and just refills the other customer's beverage. Finally, after the other customer leaves, the waiter acknowledges your existence and helps you. So what is the problem? The waiter hasn't been fired, that's the problem. Actually, the problem is that the waiter didn't multitask. A multitasking waiter could serve two or more customers at once instead of waiting for one customer to finish before serving a new customer. The multitasking waiter is a rough analogy to how threads work in computer science. In this chapter, we go over all about how Java threads work and how to synchronize them, and we teach you the tips and tricks along the way.