synchronized的常见使用方式
修饰代码块(同步代码块)
synchronized (object) {
//具体代码
}
修饰方法
synchronized void test(){
//具体代码
}
synchronized不能继承?(插曲)
父类A:
public class A {
synchronized void test() throws Exception {
try {
System.out.println("main 下一步 sleep begin threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("main 下一步 sleep end threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
}
}
子类B:(未重写test方法)
public class B extends A {
}
子类C:(重写test方法)
public class C extends A {
@Override
void test() throws Exception{
try {
System.out.println("sub 下一步 sleep begin threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("sub 下一步 sleep end threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
}
}
线程A:
public class ThreadA extends Thread {
private A a;
public void setter (A a) {
this.a = a;
}
@Override
public void run() {
try{
a.test();
}catch (Exception e){
}
}
}
线程B:
public class ThreadB extends Thread {
private B b;
public void setB(B b){
this.b=b;
}
@Override
public void run() {
try{
b.test();
}catch (Exception e){
}
}
}
线程C:
public class ThreadC extends Thread{
private C c;
public void setC(C c){
this.c=c;
}
@Override
public void run() {
try{
c.test();
}catch (Exception e){
}
}
}
测试类test:
public class test {
public static void main(String[] args) throws Exception {
A a = new A();
ThreadA A1 = new ThreadA();
A1.setter(a);
A1.setName("A1");
A1.start();
ThreadA A2 = new ThreadA();
A2.setter(a);
A2.setName("A2");
A2.start();
A1.join();
A2.join();
System.out.println("=============");
B b = new B();
ThreadB B1 = new ThreadB();
B1.setB(b);
B1.setName("B1");
B1.start();
ThreadB B2 = new ThreadB();
B2.setB(b);
B2.setName("B2");
B2.start();
B1.join();
B2.join();
System.out.println("=============");
C c = new C();
ThreadC C1 = new ThreadC();
C1.setName("C1");
C1.setC(c);
C1.start();
ThreadC C2 = new ThreadC();
C2.setName("C2");
C2.setC(c);
C2.start();
C1.join();
C2.join();
}
}
运行结果:
子类B继承了父类A,但是没有重写test方法,ThreadB仍然是同步的。子类C继承了父类A,也重写了test方法,但是未明确写上synchronized,所以这个方法并不是同步方法。只有显式的写上synchronized关键字,才是同步方法。
所以synchronized不能继承这句话有歧义,我们只要记住子类如果想要重写父类的同步方法,synchronized关键字一定要显示写出,否则无效。
修饰静态方法
synchronized static void test(){
//具体代码
}
修饰类
synchronized (Example2.class) {
//具体代码
}