Java多线程并发编程 Synchronized关键字
发布时间 - 2026-01-11 01:14:28 点击率:次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) 获得的是全局锁,两把不同的锁,所以不能达到同步效果。
# Java
# Synchronized
# 关键字
# Java中synchronized用法汇总
# Java并发系列之JUC中的Lock锁与synchronized同步代码块问题
# Java中线程状态+线程安全问题+synchronized的用法详解
# Java中提供synchronized后为什么还要提供Lock
# Java 深入浅出分析Synchronized原理与Callable接口
# Java对象级别与类级别的同步锁synchronized语法示例
# Java synchronized同步方法详解
# Java多线程之synchronized同步代码块详解
# Java多线程并发synchronized 关键字
# 的是
# 都是
# 锁住
# 时将
# 他们的
# 都有
# 这两个
# 才有
# 将被
# 而非
# 正因
# 不属于
# 能再
# 可以达到
# 时应
# 暂不
# 两把
# 也去
# 不同之处
# 写一篇
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
Laravel如何理解并使用服务容器(Service Container)_Laravel依赖注入与容器绑定说明
Laravel怎么使用Session存储数据_Laravel会话管理与自定义驱动配置【详解】
Laravel如何安装Breeze扩展包_Laravel用户注册登录功能快速实现【流程】
如何在腾讯云免费申请建站?
Laravel如何实现API资源集合?(Resource Collection教程)
Laravel怎么配置S3云存储驱动_Laravel集成阿里云OSS或AWS S3存储桶【教程】
Linux系统运维自动化项目教程_Ansible批量管理实战
如何在新浪SAE免费搭建个人博客?
微信小程序 五星评分(包括半颗星评分)实例代码
Laravel怎么发送邮件_Laravel Mail类SMTP配置教程
UC浏览器如何设置启动页 UC浏览器启动页设置方法
如何在橙子建站中快速调整背景颜色?
QQ浏览器网页版登录入口 个人中心在线进入
laravel怎么配置和使用PHP-FPM来优化性能_laravel PHP-FPM配置与性能优化方法
专业企业网站设计制作公司,如何理解商贸企业的统一配送和分销网络建设?
桂林网站制作公司有哪些,桂林马拉松怎么报名?
微信小程序 input输入框控件详解及实例(多种示例)
什么是JavaScript解构赋值_解构赋值有哪些实用技巧
Laravel如何实现密码重置功能_Laravel密码找回与重置流程
laravel服务容器和依赖注入怎么理解_laravel服务容器与依赖注入解析
如何在云主机快速搭建网站站点?
Laravel如何处理和验证JSON类型的数据库字段
如何在万网利用已有域名快速建站?
Python图片处理进阶教程_Pillow滤镜与图像增强
Java解压缩zip - 解压缩多个文件或文件夹实例
Android 常见的图片加载框架详细介绍
JavaScript如何实现路由_前端路由原理是什么
Laravel如何实现多对多模型关联?(Eloquent教程)
百度浏览器ai对话怎么关 百度浏览器ai聊天窗口隐藏
如何在自有机房高效搭建专业网站?
jQuery中的100个技巧汇总
免费网站制作appp,免费制作app哪个平台好?
Laravel如何获取当前用户信息_Laravel Auth门面获取用户ID
怎样使用JSON进行数据交换_它有什么限制
php 三元运算符实例详细介绍
微信小程序 scroll-view组件实现列表页实例代码
简单实现Android文件上传
网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?
想要更高端的建设网站,这些原则一定要坚持!
如何在万网ECS上快速搭建专属网站?
Laravel如何使用withoutEvents方法临时禁用模型事件
Laravel定时任务怎么设置_Laravel Crontab调度器配置
香港网站服务器数量如何影响SEO优化效果?
Laravel如何获取当前登录用户信息_Laravel Auth门面使用与Session用户读取【技巧】
高端网站建设与定制开发一站式解决方案 中企动力
极客网站有哪些,DoNews、36氪、爱范儿、虎嗅、雷锋网、极客公园这些互联网媒体网站有什么差异?
Win10如何卸载预装Edge扩展_Win10卸载Edge扩展教程【方法】
如何为不同团队 ID 动态生成多个“认领值班”按钮
如何在服务器上配置二级域名建站?
简单实现Android验证码

