这一章节我们来讨论一下通过同步代码块证明synchronized标记的是对象锁。
1.代码清单:
package com.ray.deepintothread.ch02.topic_11;
/**
*
* @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 {
public void updateA() throws InterruptedException {
synchronized (this) {
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 (this) {
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:1462281771917
updateA endTime:1462281772917
updateB startTime:1462281772917
updateB endTime:1462281773917
从上面的输出我们可以看出,两个线程同时执行,但是执行updateB的开始时间确实updateA的结束时间
换一个更加明显的例子:
输出:
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
从上面的输出我们可以看见,两个线程的执行是有先后顺序,只有等另一个执行完了,才执行下一个
2.结论:synchronized标记的是对象锁
总结:这一章节我们通过同步代码块证明synchronized标记的是对象锁。
这一章节就到这里,谢谢
------------------------------------------------------------------------------------
我的github:https://github.com/raylee2015/DeepIntoThread
目录:http://blog.csdn.net/raylee2007/article/details/51204573