多线程执行父类和子类中的同步方法的结论

xiaoxiao2021-02-28  85

结论:

父类和子类中分别有一个同步方法(没有重写),然后开启两个线程分别执行其中一个同步方法,最终结果是串行。结论:父类和子类中的同步方法是同一个锁。测试代码如下:

SynParent.java public class SynParent {     public synchronized void synParent(){         try {             Thread.sleep(1000);         }catch (InterruptedException e){             e.printStackTrace();         }         System.out.printf("父类同步方法输出---------->结束时间:"+System.currentTimeMillis()+"\n");     } } SynChild.java public class SynChild extends SynParent{     public synchronized void synChild(){         try {             Thread.sleep(2000);         }catch (InterruptedException e){             e.printStackTrace();         }         System.out.printf("子类同步方法输出---------->结束时间:"+System.currentTimeMillis()+"\n");     } } SynParentAndChildTest.java public class SynParentAndChildTest extends Thread{     SynChild synChild;     int index;     public SynParentAndChildTest(SynChild synChild,int index) {         this.synChild = synChild;         this.index = index;     }     @Override     public void run() {         super.run();         if (0 == index){             System.out.printf("开始执行父类方法------>时间:"+System.currentTimeMillis()+"\n");             synChild.synParent();         }else {             System.out.printf("开始执行子类方法------>时间:"+System.currentTimeMillis()+"\n");             synChild.synChild();         }     } } main: private static void synParentAndChildTest(){         SynChild synChild = new SynChild();         for (int i = 0; i < 2; i++){             SynParentAndChildTest synParentAndChildTest = new SynParentAndChildTest(synChild,i);             synParentAndChildTest.start();         }

  }

结果:

转载请注明原文地址: https://www.6miu.com/read-33662.html

最新回复(0)