Java Reference
In-Depth Information
is resolved. The following code creates two threads that each push the
int
s
1
to
5
onto
the same
MyStack2
object, except this time the threads do not interfere with each other.
The
Pusher2
class is the same as
Pusher
from earlier except it has a fi eld of type
MyStack2
instead of
MyStack
.
MyStack2 stack = new MyStack2();
Pusher2 one = new Pusher2(stack);
Pusher2 two = new Pusher2(stack);
one.start();
two.start();
try {
one.join();
two.join();
}catch(InterruptedException e) {}
System.out.println(stack.toString());
Here is a sample output:
1 1 2 2 3 3 4 4 5 5
Because the
MyStack2
object has synchronized methods, the
push
and
pop
methods
successfully modify the
values
and
index
fi elds of
MyStack2
without leaving the object in
an inconsistent state.
Now that we have seen the
synchronized
keyword, we can discuss the
wait
and
notify
methods of the
Object
class. These two methods can only be invoked within a
synchronized block of code, and they provide a communication mechanism between
threads that need to work concurrently.
The
wait
,
notify
, and
notifyAll
Methods
The
wait
,
notify
, and
notifyAll
methods are defi ned in the
Object
class, so they can
be invoked on any Java object. As we discussed in the “Thread States” section, the
wait
method causes the current thread to stop running until another thread calls
notify
or
notifyAll
on the same object that the waiting thread called
wait
on. You should know the
following two important details about
wait
,
notify
, and
notifyAll
:
A thread can only invoke
wait
,
notify
, or
notifyAll
on an object if the thread
owns the object's monitor lock. In other words, these methods must be invoked in
synchronized code.
Search WWH ::
Custom Search