码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程之深入理解synchronize关键字

时间:2018-08-20 21:48:32      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:stat   not   number   keyword   方法   rac   成功   调用   code   

synchronize锁重入:

 

关键字synchronize拥有锁重入的功能,也就是在使用synchronize时,当一个线程的得到了一个对象的锁后,再次请求此对象是可以再次得到该对象的锁。 
当一个线程请求一个由其他线程持有的锁时,发出请求的线程就会被阻塞,然而,由于内置锁是可重入的,因此如果某个线程试图获得一个已经由她自己持有的锁,那么这个请求就会成功,“重入” 意味着获取锁的 操作的粒度是“线程”,而不是调用。

public class SyncDubbol {

    public synchronized void method1(){
        System.out.println("method1....");
        method2();
    }
    public synchronized void method2(){
        System.out.println("method2....");
        method3();
    }
    public synchronized void method3(){
        System.out.println("method3....");
    }

    public static void main(String[] args) {
        final SyncDubbol sd=new SyncDubbol();
        new Thread(new Runnable() {
            @Override
            public void run() {
                sd.method1();
            }
        }).start();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

上面的代码虽然三个方法都是被synchronize修饰,但是在执行method1方法时已经得到对象的锁,所以在执行method2方法时无需等待,直接获得锁,因此这个方法的执行结果是

method1....
method2....
method3....
  • 1
  • 2
  • 3

如果内置锁不是可重入的,那么这段代码将发生死锁。

public class Widget{
    public synchronized void dosomething(){
        System.out.println("dosomthing");
    }
}
public class LoggingWidget extends Widget{
    public synchronized void dosomething(){
        System.out.println("calling dosomthing");
        super.dosomething();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Java多线程之深入理解synchronize关键字

标签:stat   not   number   keyword   方法   rac   成功   调用   code   

原文地址:https://www.cnblogs.com/PrestonL/p/9507938.html

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