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

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

时间:2016-05-07 07:24:54      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

这一章节我们来讨论一下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;
	}

	@Override
	public void run() {
		try {
			myService.updateA();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ThreadTwo implements Runnable {

	private MyService myService;

	public ThreadTwo(MyService myService) {
		this.myService = myService;
	}

	@Override
	public 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

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

标签:

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

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