Re: a simple multi-thread question
John <xsli2@yahoo.com> writes:
synchronized private void print()
{
System.out.println("printing A");
System.out.println("printing B");
System.out.println("printing C");
}
Like others said, this will lock on the individual object, the instance
of the class that defines the print() method, and if you have two
instances of that class, they can execute the method without blocking
each other. And one way of preventing different threads is to make the
method static.
However, if you need to use instance variables in the method or
for some other reason can't make the method static, you can define a
static lock object and synchronize a code block on that, as long as the
threads run on the same JVM.
This way (I didn't test this snippet now, so there may be some bug, but
it should work something like this):
private static final Object synchroLock = new Object();
private void print() {
// possibly some code that will not be synchronized
synchronized (synchroLock) {
System.out.println("printing A");
System.out.println("printing B");
System.out.println("printing C");
}
// possibly some more code that will not be synchronized
}
You must make the synchroLock object static, so it CAN be shared with
all instances of the class, and you should make it final to make sure
that it can't be instantiated after the classloader instantiates it.
If the synchroLock gets instantiated again, the synchronization will not
work between class instances having separate instances of synchroLock.
--
Jukka Lahtinen