[英]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
.它只是将方法体包装在同步于
this
或TheEnclosingClass.class
的块中的TheEnclosingClass.class
。
This has a couple of consequences for methods in subclasses:这对子类中的方法有几个后果:
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.