Java 多线程 - Synchronized关键字
目录
1-Synchronized 关键字概述
2- Synchronized关键字作用域
3- Synchronized 原理(反编译指令解释)
正文
1-Synchronized 关键字概述
由于同一进程的多个线程共享同一片存储空间,在带来方便的同时,也带来了访问冲突这个严重的问题。Java语言提供了专门机制以解决这种冲突,有效避免了同一个数据对象被多个线程同时访问。
需要明确的几个问题:
- synchronized关键字可以作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块。如果 再细的分类,synchronized可作用于instance变量、object reference(对象引用)、static函数和class literals(类名称字面常量)身上。
- 无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问。
- 每个对象只有一个锁(lock)与之相关联。
- 实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。
2- Synchronized关键字作用域
Java中每一个对象都可以作为锁,这是synchronized实现同步的基础:
- 普通同步方法,锁是当前实例对象
- 静态同步方法,锁是当前类的class对象
- 同步方法块,锁是括号里面的对象
1、普通同步方法,锁是当前实例对象
public class SynchronizedTest {
4 public synchronized void method1(){
5 System.out.println("Method 1 start");
6 try {
7 System.out.println("Method 1 execute");
8 Thread.sleep(3000);
9 } catch (InterruptedException e) {
10 e.printStackTrace();
11 }
12 System.out.println("Method 1 end");
13 }
14
15 public synchronized void method2(){
16 System.out.println("Method 2 start");
17 try {
18 System.out.println("Method 2 execute");
19 Thread.sleep(1000);
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 }
23 System.out.println("Method 2 end");
24 }
25
26 public static void main(String[] args) {
27 final SynchronizedTest test = new SynchronizedTest();
28
29 new Thread(new Runnable() {
30 @Override
31 public void run() {
32 test.method1();
33 }
34 }).start();
35
36 new Thread(new Runnable() {
37 @Override
38 public void run() {
39 test.method2();
40 }
41 }).start();
42 }
43 }
结果:
线程2需要等待线程1的method1执行完成才能开始执行method2方法。 Method 1 start
Method 1 execute
Method 1 end
Method 2 start
Method 2 execute
Method 2 end
2、静态同步方法,锁是当前类的class对象
public class SynchronizedTest {
4 public static synchronized void method1(){
5 System.out.println("Method 1 start");
6 try {
7 System.out.println("Method 1 execute");
8 Thread.sleep(3000);
9 } catch (InterruptedException e) {
10 e.printStackTrace();
11 }
12 System.out.println("Method 1 end");
13 }
14
15 public static synchronized void method2(){
16 System.out.println("Method 2 start");
17 try {
18 System.out.println("Method 2 execute");
19 Thread.sleep(1000);
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 }
23 System.out.println("Method 2 end");
24 }
25
26 public static void main(String[] args) {
27 final SynchronizedTest test = new SynchronizedTest();
28 final SynchronizedTest test2 = new SynchronizedTest();
29
30 new Thread(new Runnable() {
31 @Override
32 public void run() {
33 test.method1();
34 }
35 }).start();
36
37 new Thread(new Runnable() {
38 @Override
39 public void run() {
40 test2.method2();
41 }
42 }).start();
43 }
44 }
结果:
执行结果如下,对静态方法的同步本质上是对类的同步(静态方法本质上是属于类的方法,而不是对象上的方法),
所以即使test和test2属于不同的对象,但是它们都属于SynchronizedTest类的实例,所以也只能顺序的执行method1和method2,不能并发执行。 Method 1 start
Method 1 execute
Method 1 end
Method 2 start
Method 2 execute
Method 2 end
3、同步方法块,锁是括号里面的对象
3.1 同步到单个对象锁
package com.zj.lock;
import java.util.concurrent.TimeUnit; public class Resource1 {
public void f() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in f()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in f()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public void g() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in g()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in g()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public void h() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in h()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in h()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) {
final Resource1 rs = new Resource1(); new Thread() {
public void run() {
rs.f();
}
}.start(); new Thread() {
public void run() {
rs.g();
}
}.start(); rs.h();
}
}
结果:
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
Thread-1:not synchronized in g()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
注意:
1)当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
2)然而,当一个线程访问object的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的非synchronized (this)同步代码块。
3)尤其关键的是,当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对object中所有其它synchronized(this) 同步代码块的访问将被阻塞。
3.2 同步到多个对象锁
package com.zj.lock;
import java.util.concurrent.TimeUnit; public class Resource2 {
private Object syncObject1 = new Object();
private Object syncObject2 = new Object(); public void f() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in f()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in f()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public void g() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in g()");
synchronized (syncObject1) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in g()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public void h() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in h()");
synchronized (syncObject2) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in h()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) {
final Resource2 rs = new Resource2(); new Thread() {
public void run() {
rs.f();
}
}.start(); new Thread() {
public void run() {
rs.g();
}
}.start(); rs.h();
}
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
main:synchronized in h()
Thread-1:not synchronized in g()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
package com.zj.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class Resource3 {
private Lock lock = new ReentrantLock(); public void f() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in f()");
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in f()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
} public void g() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in g()");
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in g()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
} public void h() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in h()");
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in h()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
} public static void main(String[] args) {
final Resource3 rs = new Resource3(); new Thread() {
public void run() {
rs.f();
}
}.start(); new Thread() {
public void run() {
rs.g();
}
}.start(); rs.h();
}
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
Thread-1:not synchronized in g()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Resource4.java
package com.zj.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class Resource4 {
private Lock lock1 = new ReentrantLock();
private Lock lock2 = new ReentrantLock();
private Lock lock3 = new ReentrantLock(); public void f() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in f()");
lock1.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in f()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock1.unlock();
}
} public void g() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in g()");
lock2.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in g()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock2.unlock();
}
} public void h() {
// other operations should not be locked...
System.out.println(Thread.currentThread().getName()
+ ":not synchronized in h()");
lock3.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in h()");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock3.unlock();
}
} public static void main(String[] args) {
final Resource4 rs = new Resource4(); new Thread() {
public void run() {
rs.f();
}
}.start(); new Thread() {
public void run() {
rs.g();
}
}.start(); rs.h();
}
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
main:synchronized in h()
Thread-1:not synchronized in g()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
3- Synchronized 原理(反编译decompile指令解释)
package com.paddx.test.concurrent; public class SynchronizedDemo {
public void method() {
synchronized (this) {
System.out.println("Method 1 start");
}
}
}
反编译结果:
关于这两条指令的作用,我们直接参考JVM规范中描述:
monitorenter :
Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
• If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
• If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
• If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.
这段话的大概意思为:
每个对象有一个监视器锁(monitor)。当monitor被占用时就会处于锁定状态,线程执行monitorenter指令时尝试获取monitor的所有权,过程如下:
1、如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者。
2、如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1.
3.如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入数为0,再重新尝试获取monitor的所有权。
monitorexit:
The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.
这段话的大概意思为:
执行monitorexit的线程必须是objectref所对应的monitor的所有者。
指令执行时,monitor的进入数减1,如果减1后进入数为0,那线程退出monitor,不再是这个monitor的所有者。其他被这个monitor阻塞的线程可以尝试去获取这个 monitor 的所有权。
通过这两段描述,我们应该能很清楚的看出Synchronized的实现原理,Synchronized的语义底层是通过一个monitor的对象来完成,其实wait/notify等方法也依赖于monitor对象,这就是为什么只有在同步的块或者方法中才能调用wait/notify等方法,否则会抛出java.lang.IllegalMonitorStateException的异常的原因。
我们再来看一下同步方法的反编译结果:
源代码:
package com.paddx.test.concurrent; public class SynchronizedMethod {
public synchronized void method() {
System.out.println("Hello World!");
}
}
反编译结果:
从反编译的结果来看,方法的同步并没有通过指令monitorenter和monitorexit来完成(理论上其实也可以通过这两条指令来实现),不过相对于普通方法,其常量池中多了ACC_SYNCHRONIZED标示符。JVM就是根据该标示符来实现方法的同步的:当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,如果设置了,执行线程将先获取monitor,获取成功之后才能执行方法体,方法执行完后再释放monitor。在方法执行期间,其他任何线程都无法再获得同一个monitor对象。 其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需通过字节码Bytecode 来完成。
引用文章
作者:liuxiaopeng
博客地址:http://www.cnblogs.com/paddix/
作者:DanieX
链接:https://www.jianshu.com/p/ea9a482ece5f
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
作者:hanwei_java
来源:CSDN
原文:https://blog.csdn.net/hanwei_java/article/details/79738614
版权声明:本文为博主原创文章,转载请附上博文链接!
Java 多线程 - Synchronized关键字的更多相关文章
- Java 多线程 —— synchronized关键字
java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...
- Java多线程synchronized关键字
synchronized关键字代表着同步的意思,在Java中被synchronized修饰的有三种情况 1.同步代码块 //锁为objsynchronized(obj){ while(true){ i ...
- Java多线程-synchronized关键字
进程:是一个正在执行中的程序.每一个进程执行都有一个执行顺序.该顺序是一个执行路径,或者叫一个控制单元. 线程:就是进程中的一个独立的控制单元.线程在控制着进程的执行. 一个进程中至少有一个线程 Ja ...
- java多线程 synchronized关键字的一些用法
看这篇文章啦: http://blog.csdn.net/xiao__gui/article/details/8188833
- Java的synchronized关键字:同步机制总结
JAVA中synchronized关键字能够作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块.搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程 ...
- Java 多线程 - synchronize 关键字
目录 Java 多线程 - synchronize 关键字 Java 多线程 - synchronize 关键字 学习自 http://cmsblogs.com/?p=2071 https://www ...
- java基础Synchronized关键字之对象锁
java中Synchronized关键字之对象锁 当有多个线程对一个共享数据进行操作时,需要注意多线程的安全问题. 多线程的同步机制对资源进行加锁,使得在同一个时间,只有一个线程可以进行操作,同 ...
- java中synchronized关键字分析
今天我们来分析一下java中synchronized关键字.首先来看一段java代码:(本地编译环境为mac,jdk1.8的环境) Demo.java package com.example.spri ...
- Java基础-synchronized关键字的用法(转载)
synchronized--同步 顾名思义是用于同步互斥的作用的. 这里精简的记一下它的使用方法以及意义: 当synchronized修饰 this或者非静态方法或者是一个实例的时候,所同步的锁是加在 ...
随机推荐
- xcode10下,Build Phases下没有Embed Frameworks
升级xcode10后发现,Build Phases下,找不到Embed Frameworks了,最后发现在General下,有一项“Embedded Binaries",可以在这里添加Fra ...
- JAVA 调用exe程序执行对应的文件 (个人用于编译Java文件)
需求: 需要利用Java程序,来调用计算机本身的黑窗口,来将特定的Java文件编译成对应的字节码文件. 实现思路: 通过调用Java的Runtime类,每个 Java 应用程序都有一个 Runtime ...
- ABP实践(1)-通过官方模板创建ASP.NET Core 2.x版本+vue.js单页面模板-启动运行项目
1,打开ABP官网下载模板页面 2,根据下图选择对应的选项及输入项目名 注:上图验证码下方的选择框打钩表示下载最新稳定版,不打钩表示下载最新版本(有可能是预览版) 3,解压下载的压缩包 解压之后是个a ...
- redis 开启远程访问权限
1 开启redis端口访问权限 redis默认的端口是6379,要远程访问redis服务,确保服务器上的6379端口打开. 1.1 查看打开的端口 /etc/init.d/iptables statu ...
- Hexo之傻瓜攻略
Hexo搭建个人技术博客的网站,从零开始流程 搭建篇 必备Node.js环境 安装配置hexo: npm install -g hexo 安装cli hexo init 初始化hexo npm ins ...
- MySQL学习基础知识2
1.基础语句 查 select(* | 字段名 | 四则运算 | 聚合函数) from 表名称; 加上as取别名 as可省略 如:select name, (math+english)/2 total ...
- MySql自动备份shell
MySql黑屏备份是每个运维工程师必备的技能,以下是MySQL自动备份脚本: #/bin/bash#This is mysql backup shell on 2019/4/28 BAKUP_DIR= ...
- 深入理解JVM(6)——Java内存模型和线程
Java虚拟机规范中定义了Java内存模型(Java Memory Model,JMM)用来屏蔽掉各种硬件和操作系统的内存访问差异,以实现让Java程序在各种平台下都能达到一致的内存访问效果(“即Ja ...
- STS搭建SpringBoot项目
开发工具:推荐IDEA . Spring Tool Suit 虽然很简单,但还是记录一下,图个热闹. 开始 >>> 1. File --> New --> Spring ...
- MD5算法 —— C语言实现(字符串的加密)
转 https://blog.csdn.net/weixin_42167759/article/details/81209320 网上找到的实现md5函数代码,包括一个头文件md5.h和一个源文件md ...