2.2.5synchronized代码间的同步性

时间:2023-12-05 14:04:44
package com.cky.bean;

/**
* Created by chenkaiyang on 2017/12/6.
*/
public class ObjectService {
public void serviceMethodA(){
synchronized (this) {
try {
System.out.println("a begin time="+System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("a end time="+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
} } public void serviceMethodB(){
synchronized (this) {
System.out.println("b begin time="+System.currentTimeMillis());
System.out.println("b end time="+System.currentTimeMillis());
} }
}
package com.cky.thread;

import com.cky.bean.ObjectService;

/**
* Created by chenkaiyang on 2017/12/5.
*/
public class ThreadA extends Thread{
private ObjectService service;
public ThreadA(ObjectService service) {
super();
this.service = service;
} @Override
public void run() {
super.run();
service.serviceMethodA();
}
}
package com.cky.thread;

import com.cky.bean.ObjectService;

/**
* Created by chenkaiyang on 2017/12/5.
*/
public class ThreadB extends Thread{
private ObjectService service;
public ThreadB(ObjectService service) {
super();
this.service = service;
} @Override
public void run() {
super.run();
service.serviceMethodB();
}
}
package com.cky.test;

import com.cky.bean.ObjectService;
import com.cky.thread.ThreadA;
import com.cky.thread.ThreadB; /**
* Created by chenkaiyang on 2017/12/6.
*/
public class Test2 {
public static void main(String[] args) {
ObjectService objectService = new ObjectService();
ThreadA a = new ThreadA(objectService);
a.setName("a");
ThreadB b = new ThreadB(objectService);
b.setName("b");
a.start();
b.start(); }
}
D:\it\jdk1.8\bin\java -Didea.launcher.port=7541 "-Didea.launcher.bin.path=D:\it\idea\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\it\jdk1.8\jre\lib\charsets.jar;D:\it\jdk1.8\jre\lib\deploy.jar;D:\it\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\it\jdk1.8\jre\lib\ext\cldrdata.jar;D:\it\jdk1.8\jre\lib\ext\dnsns.jar;D:\it\jdk1.8\jre\lib\ext\jaccess.jar;D:\it\jdk1.8\jre\lib\ext\jfxrt.jar;D:\it\jdk1.8\jre\lib\ext\localedata.jar;D:\it\jdk1.8\jre\lib\ext\nashorn.jar;D:\it\jdk1.8\jre\lib\ext\sunec.jar;D:\it\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\it\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\it\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\it\jdk1.8\jre\lib\ext\zipfs.jar;D:\it\jdk1.8\jre\lib\javaws.jar;D:\it\jdk1.8\jre\lib\jce.jar;D:\it\jdk1.8\jre\lib\jfr.jar;D:\it\jdk1.8\jre\lib\jfxswt.jar;D:\it\jdk1.8\jre\lib\jsse.jar;D:\it\jdk1.8\jre\lib\management-agent.jar;D:\it\jdk1.8\jre\lib\plugin.jar;D:\it\jdk1.8\jre\lib\resources.jar;D:\it\jdk1.8\jre\lib\rt.jar;F:\springboot\threaddemo\out\production\threaddemo;D:\it\idea\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test2
a begin time=1512569404772
a end time=1512569406772
b begin time=1512569406772
b end time=1512569406772

结果分析:当一个线程访问object的一个同步代码块时,其他线程对同一个object的所有其他的同步代码块将被阻塞,这说明同步代码块使用的是对象监视