Use the synchronized .
class sample { private String msg=null; public synchronized void newmsg(String x){ msg=x; } public synchronized string getmsg(){ String temp=msg; msg=null; return msg; } }
Using the synchronized for methods will require threads to get the lock on the sample instance. That way, if any one thread is in newmsg() , no other thread will be able to lock the instance of sample , even if it tried to call getmsg() .
On the other hand, using synchronized methods can become a bottleneck if your methods perform lengthy operations - all threads, even if they want to call other methods on this object that may alternate, still have to wait.
IMO, in your simple example, it's okay to use synchronized methods, since you actually have two methods that should not be interleaved. However, under various circumstances, it may make more sense to synchronize the lock object, as shown in Joh Skeet's answer.
no.good.at.coding May 2 '11 at 20:05 2011-05-02 20:05
source share