测试如下
package com.cky.bean; /** * Created by chenkaiyang on 2017/12/4. */ public class SelfPrivateNum { int num =0; synchronized public void addI(String usrName) { try { if (usrName.equals("a")) { num =100; System.out.println("a over"); Thread.sleep(2000); } else { num= 200; System.out.println("b over"); } System.out.println(usrName + " num="+ num); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.cky.thread; import com.cky.bean.SelfPrivateNum; /** * Created by chenkaiyang on 2017/12/4. */ public class ThreadA extends Thread{ private SelfPrivateNum sn; public ThreadA (SelfPrivateNum sn) { this.sn = sn; } @Override public void run() { super.run(); sn.addI("a"); } }
package com.cky.thread; import com.cky.bean.SelfPrivateNum; /** * Created by chenkaiyang on 2017/12/4. */ public class ThreadB extends Thread{ private SelfPrivateNum sn; public ThreadB (SelfPrivateNum sn) { this.sn = sn; } @Override public void run() { super.run(); sn.addI("b"); } }
package com.cky.test; import com.cky.bean.SelfPrivateNum; import com.cky.thread.ThreadA; import com.cky.thread.ThreadB; /** * Created by chenkaiyang on 2017/12/2. */ public class Test { public static void main(String[] args){ SelfPrivateNum sn1 = new SelfPrivateNum(); SelfPrivateNum sn2 = new SelfPrivateNum(); ThreadA threadA = new ThreadA(sn1); ThreadB threadB = new ThreadB(sn2); threadA.start(); threadB.start(); } }
D:itjdk1.8injava -Didea.launcher.port=7535 "-Didea.launcher.bin.path=D:itideaIntelliJ IDEA 2016.3.3in" -Dfile.encoding=UTF-8 -classpath "D:itjdk1.8jrelibcharsets.jar;D:itjdk1.8jrelibdeploy.jar;D:itjdk1.8jrelibextaccess-bridge-64.jar;D:itjdk1.8jrelibextcldrdata.jar;D:itjdk1.8jrelibextdnsns.jar;D:itjdk1.8jrelibextjaccess.jar;D:itjdk1.8jrelibextjfxrt.jar;D:itjdk1.8jrelibextlocaledata.jar;D:itjdk1.8jrelibext ashorn.jar;D:itjdk1.8jrelibextsunec.jar;D:itjdk1.8jrelibextsunjce_provider.jar;D:itjdk1.8jrelibextsunmscapi.jar;D:itjdk1.8jrelibextsunpkcs11.jar;D:itjdk1.8jrelibextzipfs.jar;D:itjdk1.8jrelibjavaws.jar;D:itjdk1.8jrelibjce.jar;D:itjdk1.8jrelibjfr.jar;D:itjdk1.8jrelibjfxswt.jar;D:itjdk1.8jrelibjsse.jar;D:itjdk1.8jrelibmanagement-agent.jar;D:itjdk1.8jrelibplugin.jar;D:itjdk1.8jrelib esources.jar;D:itjdk1.8jrelib t.jar;F:springboot hreaddemooutproduction hreaddemo;D:itideaIntelliJ IDEA 2016.3.3libidea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test a over b over b num=200 a num=100 Process finished with exit code 0
结果分析:本测试实例化了2个对象,分别开启两个线程进行访问,效果却不是同步执行的,而是异步执行,因为本实例创建了2个锁,虽然使用了synchronized关键字,但是打印顺序不是同步的,而是交叉的。
关键字synchronized取得的锁是对象锁,而非一段代码或方法的锁,哪个线程先执行该关键字的方法,哪个线程就持有该方法所属的对象的锁lock,此时其他线程等待,前提也是多个线程访问同一个对象。
如果多个线程访问的是多个对象,那么JVM会创建多个锁。