In this chapter we discuss that synchronization is not inherited.
1. Code Listing
Package com.ray.deepintothread.ch02.topic_7;/** * <br> * <br> * * @author Raylee * */public class Synchroniza tiondoesnothaveinheritance {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;} @Overridepublic void Run () {Father.service ();}} Class Threadtwo implements Runnable {private Father father;public threadtwo (Father Father) {this.father = Father;} @Overridepublic void Run () {Father.service ();}} Class Father {protected int count = 0;public synchronized void service () {for (int i = 0; i < 5; i++) {System.out.print ln ("Thread name:" + Thread.CurrentThread (). GetName () + "Count:" + count++); try {thread.sleep (100);} CaTCH (interruptedexception e) {e.printstacktrace ();}}}} Class Sub extends Father {@Overridepublic 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 ();}}}}
We see the code above, when we put the father in the task, the output:
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
We see the code above, when we put the sub in the task, the output:
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. Contrast
We compare the above two sets of output, it is obvious that the second set of output does not have synchronization properties, so we can conclude that when the subclass overrides the parent class method, if not join the synchronization flag, the same does not have synchronization.
3. Conclusion: Synchronization is not an inherited
Summary: This chapter mainly discusses that synchronization is not inherited.
This chapter is here, thank you.
------------------------------------------------------------------------------------
My github:https://github.com/raylee2015/deepintothread.
Catalog: http://blog.csdn.net/raylee2007/article/details/51204573
Learn from the beginning multithreading-2.6 synchronization is not inherited