码迷,mamicode.com
首页 > 其他好文 > 详细

对象及变量的并发访问-----synchronized同步(3)----- 锁可重入

时间:2017-10-10 13:05:00      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:art   package   sys   logs   trace   可重入锁   col   访问   run   

一、一个类中的一个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同步(3)----- 锁可重入

标签:art   package   sys   logs   trace   可重入锁   col   访问   run   

原文地址:http://www.cnblogs.com/zhc-nice/p/7644895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!