synchronized 关键字解析

同步锁依赖于对象,每个对象都有一个同步锁。

现有一成员变量 Test,当线程 A 调用 Test 的 synchronized 方法,线程 A 获得 Test 的同步锁,同时,线程 B 也去调用 Test 的 synchronized 方法,此时线程 B 无法获得 Test 的同步锁,必须等待线程 A 释放 Test 的同步锁才能获得从而执行对应方法的代码。

综上,正确使用 synchronized 关键字可确保原子性。

synchronized 关键字的特性应用

特性 1:

当线程 A 调用某对象synchronized 方法 或者 synchronized 代码块时,若同步锁未释放,其他线程调用同一对象synchronized 方法 或者 synchronized 代码块时将被阻塞,直至线程 A 释放该对象的同步锁。

DEMO1,synchronized 方法:

public class Test {

    private static class Counter {

        public synchronized void count() {
for (int i = 0; i < 6; i++) {
System.out.println(Thread.currentThread().getName() + ", i = " + i);
}
} } private static class MyThread extends Thread { private Counter mCounter; public MyThread(Counter counter) {
mCounter = counter;
} @Override
public void run() {
super.run();
mCounter.count();
}
} public static void main(String[] var0) {
Counter counter = new Counter();
// 注:myThread1 和 myThread2 是调用同一个对象 counter
MyThread myThread1 = new MyThread(counter);
MyThread myThread2 = new MyThread(counter);
myThread1.start();
myThread2.start();
} }

DEMO1 输出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5
Thread-1, i = 0
Thread-1, i = 1
Thread-1, i = 2
Thread-1, i = 3
Thread-1, i = 4
Thread-1, i = 5

DEMO2,synchronized 代码块:

public class Test {

    private static class Counter {

        public void count() {
synchronized (this) {
for (int i = 0; i < 6; i++) {
System.out.println(Thread.currentThread().getName() + ", i = " + i);
}
}
}
} private static class MyThread extends Thread { private Counter mCounter; public MyThread(Counter counter) {
mCounter = counter;
} @Override
public void run() {
super.run();
mCounter.count();
}
} public static void main(String[] var0) {
Counter counter = new Counter();
MyThread myThread1 = new MyThread(counter);
MyThread myThread2 = new MyThread(counter);
myThread1.start();
myThread2.start();
}
}

DEMO2 输出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5
Thread-1, i = 0
Thread-1, i = 1
Thread-1, i = 2
Thread-1, i = 3
Thread-1, i = 4
Thread-1, i = 5

可见,当同步锁未释放时,其他线程将被阻塞,直至获得同步锁。

而且 DEMO1 和 DEMO2 的输出结果是一样的,synchronized 方法 和 synchronized 代码块的不同之处在于 synchronized 方法 作用域较大,作用于整个方法,而 synchronized 代码块 可控制具体的作用域,更精准控制提高效率。(毕竟阻塞的都是时间啊)

DEMO3,仅修改 main 方法:

    public static void main(String[] var0) {
// 注意:myThread1 和 myThread2 传入的 Counter 是两个不同的对象
MyThread myThread1 = new MyThread(new Counter());
MyThread myThread2 = new MyThread(new Counter());
myThread1.start();
myThread2.start();
}

DEMO3 输出:

Thread-0, i = 0
Thread-1, i = 0
Thread-0, i = 1
Thread-1, i = 1
Thread-1, i = 2
Thread-1, i = 3
Thread-0, i = 2
Thread-1, i = 4
Thread-0, i = 3
Thread-1, i = 5
Thread-0, i = 4
Thread-0, i = 5

同步锁基于对象,只要锁的来源一致,即可达到同步的作用。所以,但对象不一样,则不能达到同步效果。

特性 2:

当线程 A 调用某对象synchronized 方法 或者 synchronized 代码块时,若同步锁未释放,其他线程调用同一对象其他synchronized 方法 或者 synchronized 代码块时将被阻塞,直至线程 A 释放该对象的同步锁。(注意:重点是其他

DEMO4,仅修改 doOtherThings 方法的修饰:

public class Test {

    private static class Counter {

        public synchronized void count() {
System.out.println(Thread.currentThread().getName() + " sleep");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " awake");
} public synchronized void doOtherThings(){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}
} public static void main(String[] var0) {
final Counter counter = new Counter();
new Thread(new Runnable() {
@Override
public void run() {
counter.count();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
counter.doOtherThings();
}
}).start();
}
}

DEMO4 输出:

Thread-0 sleep
Thread-0 awake
Thread-1 doOtherThings

可见,synchronized 获得的同步锁并非仅仅锁住代码,而是锁住整个对象。

此时应提及 happens-before 原则,正因 happens-before 原则的存在才有此现象的发生。
happens-before 原则的其中一条:

管理锁定原则:一个 unLock 操作先行发生于后面对同一个锁的 lock 操作。
(此处暂不作过多解释,解释起来能再写一篇文章了)

DEMO5,仅修改 doOtherThings 方法:

        public void doOtherThings(){
synchronized (this){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}
}

DEMO5 输出:

Thread-0 sleep
Thread-0 awake
Thread-1 doOtherThings

DEMO4 和 DEMO5 的输出结果竟然一致!没错,因为他们的同步锁来源一致(都是本实例自己),所以可以达到同步效果。

// 这两个 synchronized 锁的是同一个对象
public synchronized void count(){};
public void doOtherThings(){
synchronized (this){}
}

DEMO6,去掉 doOtherThings 方法的同步关键字:

public void doOtherThings(){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}

DEMO6 输出:

Thread-0 sleep
Thread-1 doOtherThings
Thread-0 awake

当线程 A 调用某对象synchronized 方法 或者 synchronized 代码块时,无论同步锁是否释放,其他线程调用同一对象其他 非 synchronized 方法 或者 非 synchronized 代码块时可立即调用。

实例锁和全局锁

以上 DEMO 实现的都是实例锁。锁住(作用域)的是具体某一对象实例。

什么是全局锁?

锁住整个 Class,而非某个对象或实例。

注:单例型的实例锁不属于全局锁。

全局锁的实现:

静态 synchronized 方法

DEMO7:

public class Test {

    private static class Counter {

        public static synchronized void count() {
System.out.println(Thread.currentThread().getName() + " sleep");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " awake");
} public static synchronized void doOtherThings(){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}
} public static void main(String[] var0) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.count();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Counter.doOtherThings();
}
}).start();
}
}

DEMO7 输出:

Thread-0 sleep
Thread-0 awake
Thread-1 doOtherThings

static 声明的方法为全局方法,与对象实例化无关,所以 static synchronized 方法为全局同步方法,与对象实例化无关。

synchronized 具体 Class 的代码块

DEMO8:

public class Test {

    private static class Counter {

        public static synchronized void count() {
System.out.println(Thread.currentThread().getName() + " sleep");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " awake");
} public void doOtherThings(){
synchronized (Counter.class){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}
}
} public static void main(String[] var0) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.count();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Counter counter = new Counter();
counter.doOtherThings();
}
}).start();
}
}

DEMO8 输出:

Thread-0 sleep
Thread-0 awake
Thread-1 doOtherThings

synchronized (Counter.class) 获得的同步锁是全局的,static synchronized 获得的同步锁也是全局的,同一个锁,所以达到同步效果。

区分 synchronized (this) 与 synchronized (Class.class)

DEMO9:

public class Test {

    private static class Counter {

        public void count() {
synchronized (this){
System.out.println(Thread.currentThread().getName() + " sleep");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " awake");
}
} public void doOtherThings(){
synchronized (Counter.class){
System.out.println(Thread.currentThread().getName() + " doOtherThings");
}
}
} public static void main(String[] var0) {
final Counter counter = new Counter();
new Thread(new Runnable() {
@Override
public void run() {
counter.count();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
counter.doOtherThings();
}
}).start();
}
}

DEMO9 输出:

Thread-0 sleep
Thread-1 doOtherThings
Thread-0 awake

synchronized (this) 获得的是具体对象实例 counter 的锁,而 synchronized (Counter.class) 获得的是全局锁,两把不同的锁,所以不能达到同步效果。

============= End

synchronized 关键字解析的更多相关文章

  1. Java线程和多线程(十四)——Synchronized关键字解析

    曾经有一个比较有趣的面试问题,那就是,关于使用synchronized关键字,是用在方法上面尾号,还是用在一个代码块上面为好? 答案就是使用锁定代码块为更好.因为这样不会锁定对象.当synchroni ...

  2. Java 多线程并发编程之 Synchronized 关键字

    synchronized 关键字解析 同步锁依赖于对象,每个对象都有一个同步锁. 现有一成员变量 Test,当线程 A 调用 Test 的 synchronized 方法,线程 A 获得 Test 的 ...

  3. Java并发之synchronized关键字深度解析(二)

    前言 本文继续[Java并发之synchronized关键字深度解析(一)]一文而来,着重介绍synchronized几种锁的特性. 一.对象头结构及锁状态标识 synchronized关键字是如何实 ...

  4. Java对象锁和类锁全面解析(多线程synchronized关键字)

    最近工作有用到一些多线程的东西,之前吧,有用到synchronized同步块,不过是别人怎么用就跟着用,并没有搞清楚锁的概念.最近也是遇到一些问题,不搞清楚锁的概念,很容易碰壁,甚至有些时候自己连用没 ...

  5. Java并发之synchronized关键字深度解析(三)

    前言 本篇主要介绍一下synchronized的批量重偏向和批量撤销机制,属于深水区,大家提前备好氧气瓶. 上一篇说完synchronized锁的膨胀过程,下面我们再延伸一下synchronized锁 ...

  6. java线程同步以及对象锁和类锁解析(多线程synchronized关键字)

    一.关于线程安全 1.是什么决定的线程安全问题? 线程安全问题基本是由全局变量及静态变量引起的. 若每个线程中对全局变量.静态变量只有读操作,而无写操作,一般来说,这个全局变量是线程安全的:若有多个线 ...

  7. Java并发编程:volatile关键字解析

    Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在 ...

  8. (转)Java并发编程:volatile关键字解析

    转:http://www.cnblogs.com/dolphin0520/p/3920373.html Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或 ...

  9. Java 多线程 —— synchronized关键字

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

随机推荐

  1. 实现h5中radio单击取消与选中

    <input type = "radio" id = "raid" name = "raname" checked = 'checke ...

  2. TCP 原理

    一.分组交换网络   古老的电话通信,一根电缆,两个用户设备通信 计算机中的两个设备节点通信:分组网络 计算机网络采取分组交换技术,意思就是我有[一块数据]要发给对方,那我会把这[一块数据]分成N份[ ...

  3. VO和DO转换(三) Dozer

    VO和DO转换(一) 工具汇总 VO和DO转换(二) BeanUtils VO和DO转换(三) Dozer VO和DO转换(四) MapStruct 可参考的资料: dozer官网 Dozer(Jav ...

  4. CentOS的el5, el6, el7代表什么

    https://www.cnblogs.com/EasonJim/p/9051851.html el: enterprise linux?

  5. java的数据类型:基本数据类型和引用数据类型

    Java数据类型的基本概念 数据类型在计算机语言里面,是对内存位置的一个抽象表达方式,可以理解为针对内存的一种抽象的表达方式. 开始接触每种语言的时候,都会存在对数据类型的认识,有复杂的,有复杂的,各 ...

  6. laravel自定义门面

    https://learnku.com/articles/19195   关于laravel门面和服务提供者使用的一点见解,门面之词,不足之处,还请多多指教. 在laravel中,我们可能需要用到自己 ...

  7. redhat7通过yum安装nginx最新版

    1.准备yum源 vi /etc/yum.repo.d/nginx.repo [nginx]name=nginx repobaseurl=http://nginx.org/packages/mainl ...

  8. list类型功能剖析

    append  向后追加 name_list=["eirc","alex","tony"] name_list.append('seven' ...

  9. PreparedStement 用户登录!

    一.准备工作 在qy66数据库下,新建一个denglu表.添加 name password  . package cn.zhouzhou; import java.sql.Connection; im ...

  10. Python——管道通信

    管道:双向通信 2个进程之间相互通信 from multiprocessing import Pipe,Process def func(conn1,conn2): conn2.close() whi ...