The Java Platform has supported multi-threaded or concurrent programming with the
- Thread Class
- Runnable interface
since Java 1.0. Java 5.0 increases that support with a comprehensive set of new utilities for concurrent programming.
Multithreading is a powerful function that allows a program to perform multiple tasks at once. Many modern applications rely on multithreading to perform background operations while the user is working on something in the foreground.
also plays an important role in processing input from graphical user interfaces.
This module introduces you to multithreading as it relates to Java.
You will learn how to create and use threads, and then you will create an applet that uses threads as a timing mechanism.
After completing the module, you will have the skills and knowledge necessary to:
- Understand the significance of threads
- Create and use threads
- Put threads to sleep
- Understand the importance of thread synchronization
In the next lesson, you will explore the basics of threads and multithreaded programming.
The following quiz question deals with the
method within the context of Java Threads.
Which of the following correctly describes the effect of calling the
method on an object?
(Assume that the calling Thread has the lock of that object.)
[Select 1 option: ]
- The thread that has called the
will not come out of the WAITING state until some other thread calls
notifyAll() on the same object or interrupts the thread.
- The object issuing the call to
wait() will halt until another object sends a
- An exception might be raised if it is not called in a synchronized block otherwise no exception will be raised.
- The thread calling wait() will be automatically synchronized with any other threads who call wait().
- None of the above
b. Note that it is not the object that calls the wait/notify but the thread.
c. It will ALWAYS raise IllegalMonitorStateException if not called in a synchronized block for that object.
d. Only if all the threads call wait on the same object.
A Thread should have the monitor
of that object before calling wait() on it. So if a thread synchronizes on some object and calls
on another object, then it will throw an IllegalMonitorStateException
Once a thread calls
on an object, it will wait until this thread is asked to come out of the wait state. This happens when any of the following happens.
- the time in milliseconds passed in as a parameter to wait() elapses.
- some other thread calls notifyAll on the same object.
- some other thread calls notify on the same object AND the JVM picks this particular thread (out of all the threads that might have called wait() on the same object) to wake up.
- some other thread calls this thread's interrupt method.
In all the above cases, the waiting thread comes out of the WAITING state but goes into BLOCKED state.
It must still reacquire the lock before continuing further (because it is still within the synchronized block).