as i said ,
what is the difference between
pu开发者_如何学Goblic static synchronized ..
and
public static
?
any example ?
synchronized keyword ensures that a method can be invoked by only one thread at a time. If you don't put synchronized, it is not essentially Thread-safe.
One point you have to be careful about (several programmers generally fall in that trap) is that there is no link between synchronized static methods and non synchronized static methods, ie:
class A {
public static synchronized f() {...} //class level lock
public static g() {...} //object level lock
}
public class TestA{
public static void main(String[] args){
A a = new A();
//Thread 1:
a.f();
//Thread 2:
a.g();
}
}
f() and g() are not synchronized with each other and thus can execute totally concurrently.
- static synchronized - on a method obtain a lock on the Class
static
static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
精彩评论