java 公共静态同步和公共静态有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5090464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:21:32  来源:igfitidea点击:

what is the difference between public static synchronized and public static?

java

提问by Umesh K

as i said , what is the difference between public static synchronized ..and public static ? any example ?

正如我所说,public static synchronized ..和 之间有什么区别 public static ?任何例子?

回答by adarshr

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.

synchronized 关键字确保一个方法一次只能被一个线程调用。如果您不放置同步,则它本质上不是线程安全的。

回答by Dead Programmer

  • 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.

  • 静态同步 - 在方法上获得对类的锁
  • 静止的

    静态意味着每个类一个,而不是每个对象一个,无论一个类可能存在多少个实例。这意味着您可以在不创建类的实例的情况下使用它们。静态方法是隐式最终的,因为覆盖是基于对象的类型完成的,并且静态方法附加到类,而不是对象。只要原始方法未声明为 final,超类中的静态方法就可以被子类中的另一个静态方法遮蔽。但是,您不能使用非静态方法覆盖静态方法。换句话说,您不能将静态方法更改为子类中的实例方法。

回答by Umesh K

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.

f() 和 g() 彼此不同步,因此可以完全并发执行。