对象及变量的并发访问-----synchronized同步----- 锁可重入
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象及变量的并发访问-----synchronized同步----- 锁可重入相关的知识,希望对你有一定的参考价值。
一、一个类中的一个synchronized方法调用本类中其他的synchronized方法,可以得到锁的
类中synchronized方法一调用本类中synchronized方法二
package service; /** * Created by zhc on 2017/10/10 */ public class Service3 { synchronized public void service1(){ System.out.println("service1"); service2(); } synchronized public void service2(){ System.out.println("service2"); } }
thread的run方法中实例Service,调用service1方法
package extthread; import service.Service3; /** * Created by zhc on 2017/10/10 */ public class ThreadD extends Thread{ @Override public void run() { super.run(); Service3 service = new Service3(); service.service1(); } }
run
package test; import extthread.ThreadD; /** * Created by zhc on 2017/10/10 */ public class Run3 { public static void main(String[] args) { ThreadD thread = new ThreadD(); thread.start(); } }
测试结果:
service1
service2
synchronized修饰的方法可以调用本类中其他的synchronized方法
二、可重入锁还可以用父子类继承的环境中
父类
package service; /** * Created by zhc on 2017/10/10 */ public class Father { public int i = 10; synchronized public void operate(){ try { i--; System.out.println("main print i =" + i); Thread.sleep(200); }catch (InterruptedException e){ e.printStackTrace(); } } }
子类
package service; /** * Created by zhc on 2017/10/10 */ public class Son extends Father { synchronized public void operateSon() { try { while (i>0){ i--; System.out.println("son print i "+i); Thread.sleep(100); this.operate(); } }catch (InterruptedException e){ e.printStackTrace(); } } }
线程调用子类方法
package extthread; import service.Son; /** * Created by zhc on 2017/10/10 */ public class ThreadE extends Thread { @Override public void run() { super.run(); Son son = new Son(); son.operateSon(); } }
run
package test; import extthread.ThreadE; /** * Created by zhc on 2017/10/10 */ public class Run4 { public static void main(String[] args) { ThreadE t = new ThreadE(); t.start(); } }
测试结果:
son print i 9
main print i =8
son print i 7
main print i =6
son print i 5
main print i =4
son print i 3
main print i =2
son print i 1
main print i =0
以上是关于对象及变量的并发访问-----synchronized同步----- 锁可重入的主要内容,如果未能解决你的问题,请参考以下文章