标签:
这一章节我们来讨论一下同步是不具备继承性的。
1.代码清单
package com.ray.deepintothread.ch02.topic_7; /** * <br> * <br> * * @author RayLee * */ public class SynchronizationDoesNotHaveInheritance { public static void main(String[] args) throws InterruptedException { Sub sub = new Sub(); Father father = new Father(); ThreadOne threadOne = new ThreadOne(sub); Thread thread = new Thread(threadOne); thread.start(); ThreadTwo threadTwo = new ThreadTwo(sub); Thread thread2 = new Thread(threadTwo); thread2.start(); } } class ThreadOne implements Runnable { private Father father; public ThreadOne(Father sub) { this.father = sub; } @Override public void run() { father.service(); } } class ThreadTwo implements Runnable { private Father father; public ThreadTwo(Father father) { this.father = father; } @Override public void run() { father.service(); } } class Father { protected int count = 0; public synchronized void service() { for (int i = 0; i < 5; i++) { System.out.println("Thread name:" + Thread.currentThread().getName() + " count:" + count++); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Sub extends Father { @Override public void service() { for (int i = 0; i < 5; i++) { System.out.println("Thread name:" + Thread.currentThread().getName() + " count:" + count++); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Thread name:Thread-0 count:0
Thread name:Thread-0 count:1
Thread name:Thread-0 count:2
Thread name:Thread-0 count:3
Thread name:Thread-0 count:4
Thread name:Thread-1 count:5
Thread name:Thread-1 count:6
Thread name:Thread-1 count:7
Thread name:Thread-1 count:8
Thread name:Thread-1 count:9
我们看到上面的代码,当我们放到任务里面的是Sub时,输出:
Thread name:Thread-0 count:0
Thread name:Thread-1 count:1
Thread name:Thread-0 count:2
Thread name:Thread-1 count:2
Thread name:Thread-1 count:3
Thread name:Thread-0 count:3
Thread name:Thread-0 count:4
Thread name:Thread-1 count:4
Thread name:Thread-1 count:6
Thread name:Thread-0 count:5
2.对比
我们对比上面的两组输出,很明显的是,第二组输出不具备同步性质,因此,我们可以得出结论,当子类重写父类方法的时候,如果不加入同步标志,一样不具备同步性。
3.结论:同步是不具备继承性的
总结:这一章节主要讨论了同步是不具备继承性的。
这一章节就到这里,谢谢
------------------------------------------------------------------------------------
我的github:https://github.com/raylee2015/DeepIntoThread
目录:http://blog.csdn.net/raylee2007/article/details/51204573
标签:
原文地址:http://blog.csdn.net/raylee2007/article/details/51279840