SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
This chapter covered the required thread knowledge you'll need to apply on the certification exam. Threads can be created by either extending the Thread class or implementing the Runnable interface. The only method that must be overridden in the Runnable interface is the run() method, but the thread doesn't become a thread of execution until somebody calls the Thread object's start() method. We also looked at how the sleep() method can be used to pause a thread, and we saw that when an object goes to sleep, it holds onto any locks it acquired prior to sleeping.
We looked at five thread states: new, runnable, running, blocked/waiting/sleeping, and dead. You learned that when a thread is dead, it can never be restarted even if it's still a valid object on the heap. We saw that there is only one way a thread can transition to running, and that's from runnable. However, once running, a thread can become dead, go to sleep, wait for another thread to finish, block on an object's lock, wait for a notification, or return to runnable.
You saw how two threads acting on the same data can cause serious problems (remember Lucy and Fred's bank account?). We saw that, to let one thread execute a method, but prevent other threads from running the same object's method, we use the synchronized keyword. To coordinate activity between different threads, use the wait(), notify(), and notifyAll() methods.
Категории