关于Java同步的问题 [英] Question about Java synchronized

查看:113
本文介绍了关于Java同步的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java文档说同一个对象上的两个同步方法的调用不可能交错。我需要知道的是,synchronized是否还会阻止同一类的两个不同实例中的同步方法进行交错。

The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave". What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

例如。 class Worker有一个名为process()的方法。我们有几个Worker在自己的线程中运行的实例。我们希望防止同时运行process()方法的多个实例。 synchronized 会这样做吗?

E.g. class Worker has method called process(). We have several instances of Worker running in their own threads. We want to prevent more than one instance running the process() method simultaneously. Will synchronized do this?

谢谢。

推荐答案

否; synchronized 仅阻止多个线程同时执行相同实例中的方法。如果您有 n 个实例,则可能有 n 个线程,每个线程都在其中一个实例中执行该方法。

No; synchronized only prevents multiple threads from simultaneously executing the method in the same instance. If you have n instances, there could be n threads, each executing the method in one of the instances.

如果您需要确保只有一个线程可以跨所有实例执行该方法,您应该使方法 static ,或者使方法为非 - synchronized 而是在方法中使用 synchronized 块来锁定 private static 字段。

If you need to ensure that only one thread may execute the method across all instances, you should make the method static, or make the method non-synchronized and rather use a synchronized block inside the method to lock on a private static field.

编辑:请注意,在私有实例变量上进行同步更适合拥有 synchronized 方法或同步,以及锁定私有静态实例变量更喜欢使用静态同步方法或在 this.getClass()上同步的实例方法。原因是这个 this.getClass()是整个程序都可以访问的对象引用,所以任何人都可以同步这些对象,从而阻止想要调用你的方法的线程。

Note that synchronizing on a private instance variable is preferrable to having a synchronized method or to synchronize on this, and that locking on a private static instance variable is preferrable to having a static synchronized method or an instance method that synchronizes on this.getClass(). The reason is that this and this.getClass() are object references that are accessible throughout the program, so anybody may synchronize on these objects, and thereby block threads that want to call your method.

编辑:另外,请参阅下面的@Cugan评论 - 摘要:如果你真的想要锁定在类中,您可能希望使用 synchronized(Worker.class)而不是 synchronized(this.getClass()) ,取决于在子类化的情况下你想要的效果。

Also, see @Cowan's comment below - summary: if you really want to lock on the class, you might want to use synchronized (Worker.class) rather than synchronized (this.getClass()), depending on what effect you want in the case of subclassing.

这篇关于关于Java同步的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆