简体   繁体   English

线程子类中的同步方法

[英]Synchronized method in thread subclass

I have a class that extends thread and in whose run() another method is called.我有一个扩展线程的类,并且在其 run() 中调用了另一个方法。 I want that method to be synchronized, is it possible for a method that is defined in a thread subclass to be synchronized?我希望该方法同步,是否可以同步线程子类中定义的方法?

synchronized is not part of the method signature. synchronized不是方法签名的一部分。 It is simply a shorthand for wrapping the method body in a block synchronized on either this or TheEnclosingClass.class .它只是将方法体包装在同步于thisTheEnclosingClass.class的块中的TheEnclosingClass.class

This has a couple of consequences for methods in subclasses:这对子类中的方法有几个后果:

  • You can make an overriding method synchronized, even if the overridden method isn't.您可以使覆盖方法同步,即使覆盖方法不是同步的。
  • If you don't make the overriding method synchronized, it doesn't "inherit" the synchronized-ness from the overridden method.如果您使覆盖方法同步,则​​它不会“继承”覆盖方法的同步性。 You have to do it explicitly if you want it to be synchronized too.如果您也希望它同步,则必须明确地执行此操作。

There is no problem with that.没有问题。 The reason is that every method is called within a thread anyhow.原因是无论如何,每个方法都在一个线程内被调用。 So in a thread's method call stack, somewhere a synchronized method or block may get executed.因此,在线程的方法调用堆栈中,可能会在某处执行同步方法或块。 So, this method of yours is no different from any other that may be called in the stack.所以,你的这个方法与堆栈中可能调用的任何其他方法没有什么不同。

Short answer: There's nothing special about the Thread class, and there's nothing special about any class that you define that extends Thread .简短回答: Thread类没有什么特别之处,您定义的任何extends Thread类也没有什么特别之处。 Sure, the Thread class has methods that do things that other class methods don't do, but the same could be said of the String class or the HashMap class or any class that's worth writing.当然, Thread类的方法可以做其他类方法不做的事情,但是String类或HashMap类或任何值得编写的类也是如此。

Sure, Thread is part of the Java standard library, and your class isn't.当然, Thread是 Java 标准库的一部分,而您的类不是。 Sure, Thread belongs to the java.lang package, which actually is a little bit more special than other packages.当然, Thread属于java.lang包,这实际上一点点比其他包更特殊。 But, even despite all of that...但是,尽管如此……

...It's just a class. ……这只是一堂课。


PS, Other answers here all contain good advice. PS,这里的其他答案都包含很好的建议。 Read 'em!阅读它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM