码迷,mamicode.com
首页 > 编程语言 > 详细

从头认识多线程-2.6 同步是不具备继承性的

时间:2016-04-29 15:02:24      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

这一章节我们来讨论一下同步是不具备继承性的。

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();
			}
		}
	}
}

我们看到上面的代码,当我们放到任务里面的是Father时,输出:

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


从头认识多线程-2.6 同步是不具备继承性的

标签:

原文地址:http://blog.csdn.net/raylee2007/article/details/51279840

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!