这个问题在这里已经有了答案:
Why can't an abstract method be synchronized?
(4 个回答)
4年前关闭。
我想在线程之间同步对象,这些对象扩展了一个抽象类:
public abstract class GraphicObject {
public synchronized void test(){
//work...
}
}
class Circle extends GraphicObject {
}
class Rectangle extends GraphicObject {
}
考虑这个测试类:
public class Class {
void main(){
GraphicObject a=new Circle();
GraphicObject b=new Rectangle();
Runnable r1 = new MyThread(a);
new Thread(r1).start();
Runnable r2 = new MyThread(b);
new Thread(r2).start();
}
private class MyThread implements Runnable {
private GraphicObject g;
public MyThread(GraphicObject g) {
this.g=g;
}
public void run() {
g.test();
}
}
}
在这种情况下,
a
和 b
是具有相同抽象类的独立对象。是 test()
方法同步与否?如果一个线程调用 a.test()
是 b.test()
锁定到所有其他线程?我不希望,因为它们是不同的对象。
最佳答案
抽象方法不能同步。这是在 JLS 8.4.3 :
It is a compile-time error if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized.
覆盖抽象声明的具体方法可能是同步的;在这种情况下,它就像任何其他同步方法一样工作:它锁定
this
实例。
关于java - 抽象类中的同步方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150304/