Other way to synchronize method
How to synchronize method in jav开发者_开发百科a other than using synchronized keyword?
You could use the java.util.concurrent.locks
package, especially Lock interface:
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
See here.
Depends on you concrete needs.
See Java concurrent package for higher level synchronization abstractions. Note that they may still use synchronized
underneath ...
you can use Lock classes provided in java.util.concurrent.locks package
see http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/util/concurrent/locks/Lock.html
That depends on what you're trying to do. Are you looking out of curiosity or is there a specific reason?
If you are trying to speed up your multi-threaded methods, try synchronizing or locking around specific sections, or avoiding the threading issues altogether; make shared data final
, make static (non-shared) data ThreadLocal
, use the atomic types from java.util.concurrent.atomic
, use concurrent collections (from the java.util.concurrent
packages), etc.
BTW, the java.util.concurrent
stuff is only available in Java5 onwards, though there as a project to back-port the packages for Java 1.4 at http://backport-jsr166.sourceforge.net/
I'd recommend the the book 'Java Concurrency in Practice', by Brian Goetz.
You could also use @Synchronized from Project Lombok to generate a private field that will be used as the lock for your method.
You could use a synchronized block inside your method. This can be useful if you want two methods belonging to the same class to be synchronized separately.
private Object guard = new ...
public method(){
synchronized(guard){
\\method body
...
}
}
Although in most cases this suggests that you should really break your class up.
精彩评论