Java 多线程并发编程之 Synchronized 关键字
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
Java 多线程并发编程之 Synchronized 关键字的更多相关文章
- Java并发编程之synchronized关键字
整理一下synchronized关键字相关的知识点. 在多线程并发编程中synchronized扮演着相当重要的角色,synchronized关键字是用来控制线程同步的,可以保证在同一个时刻,只有一个 ...
- 并发编程之synchronized关键字
synchronized关键字 synchronized关键字最主要的三种使用方式的总结 1.修饰实例方法,作用于当前对象实例加锁,进入同步代码块前要获得当前对象实例的锁 2.修饰静态方法,作用于当前 ...
- 高并发编程之synchronized
一.什么是线程? 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元.一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成.另外,线程 ...
- Java并发编程之volatile关键字解析
一内存模型的相关概念 二并发编程中的三个概念 三Java内存模型 四深入剖析volatile关键字 五使用volatile关键字的场景 volatile这个关键字可能很多朋友都听说过,或许也都用过.在 ...
- Java 并发编程之volatile关键字解析
摘录 1. 计算机在执行程序时,每条指令都是在CPU中执行的,而执行指令过程中,势必涉及到数据的读取和写入.由于程序运行过程中的临时数据是存放在主存(物理内存)当中的,这时就存在一个问题,由于CPU执 ...
- Java并发编程之volatile关键字
大概是因为项目.业务的原因,工作上几乎还没有使用过多线程相关的功能,相关知识差不多都忘了,所以最近补一下基础. volatile用来修饰共享变量,volatile变量具有 synchronized 的 ...
- Java多线程(三)—— synchronized关键字详解
一.多线程的同步 1.为什么要引入同步机制 在多线程环境中,可能会有两个甚至更多的线程试图同时访问一个有限的资源.必须对这种潜在资源冲突进行预防. 解决方法:在线程使用一个资源时为其加锁即可. 访问资 ...
- Java 多线程(六) synchronized关键字详解
多线程的同步机制对资源进行加锁,使得在同一个时间,只有一个线程可以进行操作,同步用以解决多个线程同时访问时可能出现的问题. 同步机制可以使用synchronized关键字实现. 当synchroniz ...
- 并发编程之synchronized锁(一)
一.设计同步器的意义 多线程编程中,有可能会出现多个线程同时访问同一个共享.可变资源的情况,这个资源我们称之其为临界资源:这种资源可能是:对象.变量.文件等. 共享:资源可以由多个线程同时访问 可变: ...
随机推荐
- Deadlock found when trying to get lock; try restarting transaction
1.错误描述 [ERROR:]2015-06-09 16:56:19,481 [抄送失败] org.hibernate.exception.LockAcquisitionException: erro ...
- linux下的APK反编译软件及过程介绍 .
需要工具: 1.apktool apk打包工具 下载地址:http://android-apktool.googlecode.com/files/apktool1.5.2.tar.bz2 安装:直接解 ...
- Linux集群问题~浅谈
系统扩展的方式 # scale up 向上扩展 # scale out 向外扩展 集群类型 LB 负载均衡集群 Load Balancing HA 高可用集群 High Availability HP ...
- JavaScript设计模式(3)-工厂模式
工厂模式 1. 简单工厂 简单工厂:使用一个类或对象封装实例化操作 假如我们有个自行车商店类 BicycleShop,它提供了销售自行车的方法可以选择销售两类自行车 Speedster,Comfort ...
- 用python帮朋友刷帖
0x0前言: 答应了一个朋友帮他刷贴,自己用python写了一个脚本刷. 虽然行为不好..但是缺钱用... 0x01准备: splinter模块: chrome浏览器驱动 0x02开始: 1.进入百度 ...
- NOIWC2018滚粗记
Day0 \(THUWC\)刚刚结束..顺利的滚粗了 Day1 整理一下自己咸鱼的心 下午到学校坐车出发 这次队伍浩大THUWC只有4个 又到了雅礼洋湖这个地方 路上突然多了许多有关\(NOI\)的标 ...
- [BZOJ1061] [Noi2008] 志愿者招募 (费用流)
Description 申奥成功后,布布经过不懈努力,终于成为奥组委下属公司人力资源部门的主管.布布刚上任就遇到了一个难 题:为即将启动的奥运新项目招募一批短期志愿者.经过估算,这个项目需要N 天才能 ...
- TP5模型关联问题
在使用模型关联时:假如有表 merchant商户表 m_store 店铺表 m_store_ref 商户店铺关联表 user 普通用户表 $mer = Merchant::with([ ' ...
- ASP.NET Core 一步步搭建个人网站(7)_Linux系统移植
摘要 考虑我们为什么要选择.NET Core? 因为它面向的是高性能服务器开发,抛却了 AspNet 的臃肿组件,非常轻量,加上微软的跨平台战略,对 Docker 的亲和性,对于开发人员也非常友好,所 ...
- Kafka最佳实践
一.硬件考量 1.1.内存 不建议为kafka分配超过5g的heap,因为会消耗28-30g的文件系统缓存,而是考虑为kafka的读写预留充足的buffer.Buffer大小的快速计算方法是平均磁盘写 ...