2.1.3多个对象多个锁
测试如下
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:\it\jdk1.8\bin\java -Didea.launcher.port=7535 "-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.Test a over b over b num=200 a num=100 Process finished with exit code 0
结果分析:本测试实例化了2个对象,分别开启两个线程进行访问,效果却不是同步执行的,而是异步执行,因为本实例创建了2个锁,虽然使用了synchronized关键字,但是打印顺序不是同步的,而是交叉的。
关键字synchronized取得的锁是对象锁,而非一段代码或方法的锁,哪个线程先执行该关键字的方法,哪个线程就持有该方法所属的对象的锁lock,此时其他线程等待,前提也是多个线程访问同一个对象。
如果多个线程访问的是多个对象,那么JVM会创建多个锁。