synchronized修饰一个方法

public synchronized void run() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + “:” + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Synchronized作用于整个方法的写法。
写法一:
public synchronized void method()
{

}
写法二:
public void method()
{
synchronized(this) {

}
}
在子类方法中加上synchronized关键字
class Parent {
public synchronized void method() { }
}
class Child extends Parent {
public synchronized void method() { }
}
在子类方法中调用父类的同步方法

class Parent {
public synchronized void method() { }
}
class Child extends Parent {
public void method() { super.method(); }
}
1.在定义接口方法时不能使用synchronized关键字。
2.构造方法不能使用synchronized关键字,但可以使用synchronized代码块来进行同步。

Synchronized也可修饰一个静态方法,用法如下:
public synchronized static void method() {

}

猜你喜欢

转载自blog.csdn.net/weixin_42866896/article/details/82957689
今日推荐