1.
1 public class SyncDubbo2 { 2 static class Sup{ //父类 3 public int i = 10; 4 public synchronized void operSup(){ 5 try{ 6 i--; 7 System.out.println("Sup父类 print i="+i); 8 Thread.sleep(1000); 9 } catch(InterruptedException e){ 10 e.printStackTrace(); 11 } 12 } 13 } 14 15 static class Sub extends Sup{ //子类 16 public synchronized void operSub(){ 17 try { 18 while(i > 0){ 19 i--; 20 System.out.println("sub子类 print i="+ i); 21 Thread.sleep(1000); 22 this.operSup(); 23 } 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 } 28 } 29 30 public static void main(String[] args) { 31 Thread t1 = new Thread(new Runnable() { 32 @Override 33 public void run() { 34 Sub sub = new Sub(); 35 sub.operSub(); 36 } 37 }, "t1"); 38 39 t1.start(); 40 } 41 42 /* 43 sub子类 print i=9 44 Sup父类 print i=8 45 sub子类 print i=7 46 Sup父类 print i=6 47 sub子类 print i=5 48 Sup父类 print i=4 49 sub子类 print i=3 50 Sup父类 print i=2 51 sub子类 print i=1 52 Sup父类 print i=0 53 */ 54 }
原文:http://www.cnblogs.com/bravolove/p/7944287.html