This may be a simple question,but still it is a problem for me.I am having a class that have method called task and i want to ensure only one instance of this class can run this method at a time.I have implemented it like this and am i doing it correct way?
class A{
public void task(){
synchronized(A.this){
//method stuff
}
}
}
class B{
public static void main(String a[]){
new A().task();
}
}
class C{
public static void main(String a[]){
new A().task();
}
}
If B started the task and before it completes C also came to task i want to C to wait until B completes.
so far it seems works.But i want to know is this the correct way,
thank you.
Not quite. As you have it, you guarantee that only one thread will execute
task()on a given instance at a time — but separate instances can still runtask()at the same time. That is, if you did this (in pseudo-code):Then since each thread creates a separate instance of
A, they’ll each be able to runtask()at the same time.You need to synchronize on a
staticfield (orA.class), or maketask()a static, synchronized method (in which casesynchronizedlocks based off of theClassobject).