Summary

Here are the methods we introduced in this chapter:

void wait()

Waits for a condition to occur. This is a method of the Object class and must be called from within a synchronized method or block.

void wait(long timeout)

Waits for a condition to occur. However, if the notification has not occurred in timeout milliseconds, it returns anyway. This is a method of the Object class and must be called from a synchronized block or method.

void wait(long timeout, int nanos)

Waits for a condition to occur. However, if the notification has not occurred in timeout milliseconds and nanos nanoseconds, it returns anyway. This is a method of the Object class and must be called from a synchronized block or method.

void notify()

Notifies a thread that is waiting for a condition that the condition has occurred. This is a method of the Object class and must be called from within a synchronized method or block.

void notifyAll()

Notifies all the threads waiting on the object that the condition has occurred. This is a method of the Object class and must be called from within a synchronized method or block.

void interrupt() (Java 1.1 and above only)

Sends an interruption to the specified thread. If the thread is currently blocked in a thread-related method (i.e., the sleep(), join(), or wait() methods), the thread moves to an unblocked state; otherwise, a boolean flag is simply set to indicate that the thread has been interrupted.

static boolean interrupted() (Java 1.1 and above only)

Returns a boolean that indicates whether the current thread has been interrupted. This is a static method of the Thread class and may be called through the class specifier. This method simply returns a flag that is set by the interrupt() method.

boolean isInterrupted() (Java 1.1 and above only)

Returns a boolean that indicates whether the specified thread has been interrupted. This method simply returns a flag that is set by the interrupt() method.

With these methods, we are now able to interoperate between threads in an efficient manner. Instead of just providing protection against race conditions, we now have mechanisms that allow threads to inform each other about events or conditions without resorting to polling and timeouts. While the wait and notify mechanism is the most widely used of the mechanisms in this chapter, we also have the ability to interrupt a thread no matter what the thread is doing.

The two default techniques of synchronizing data and threads within Java—the synchronized keyword and the wait and notify methods—provide simple, robust ways for threads to communicate and cooperate. Although we will examine some advanced techniques for data synchronization in Chapter 8, these default techniques are good enough for most Java programs.

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.