从头认识多线程-2.13 synchronized ()代码块不单可以用this,也可以用其他对象

来源:互联网 发布:安全防护眼镜知多少 编辑:程序博客网 时间:2024/06/05 11:59

这一章节我们来讨论一下synchronized ()代码块的另一个用法,它不单可以用this,也可以用其他对象。

1.代码清单

package com.ray.deepintothread.ch02.topic_13;/** *  * @author RayLee * */public class ObjectLock {public static void main(String[] args) throws InterruptedException {MyService myService = new MyService();ThreadOne threadOne = new ThreadOne(myService);Thread thread = new Thread(threadOne);thread.start();ThreadTwo threadTwo = new ThreadTwo(myService);Thread thread2 = new Thread(threadTwo);thread2.start();}}class ThreadOne implements Runnable {private MyService myService;public ThreadOne(MyService myService) {this.myService = myService;}@Overridepublic void run() {try {myService.updateA();} catch (InterruptedException e) {e.printStackTrace();}}}class ThreadTwo implements Runnable {private MyService myService;public ThreadTwo(MyService myService) {this.myService = myService;}@Overridepublic void run() {try {myService.updateB();} catch (InterruptedException e) {e.printStackTrace();}}}class MyService {private Object object;public MyService() {object = new Object();}public void updateA() throws InterruptedException {synchronized (object) {long startTime = System.currentTimeMillis();System.out.println("updateA startTime:" + startTime);Thread.sleep(1000);long endTime = System.currentTimeMillis();System.out.println("updateA endTime:" + endTime);}}public void updateB() throws InterruptedException {synchronized (object) {long startTime = System.currentTimeMillis();System.out.println("updateB startTime:" + startTime);Thread.sleep(1000);long endTime = System.currentTimeMillis();System.out.println("updateB endTime:" + endTime);}}}

输出:

updateA startTime:1462455786957
updateA endTime:1462455787958
updateB startTime:1462455787958
updateB endTime:1462455788958


2.结论

从输出可以看见,跟前面章节的代码相比,我们把synchronized ()里面的this换成一个new Object(),而且这个object不一定是object,可以是任何对象


总结:这一章节展示了synchronized ()代码块的另一个用法,它不单可以用this,也可以用其他对象。



这一章节就到这里,谢谢

------------------------------------------------------------------------------------

我的github:https://github.com/raylee2015/DeepIntoThread


目录:http://blog.csdn.net/raylee2007/article/details/51204573



这一章节就到这里,谢谢

------------------------------------------------------------------------------------

我的github:https://github.com/raylee2015/DeepIntoThread


目录:http://blog.csdn.net/raylee2007/article/details/51204573

0 0