JAVA深化篇_32—— 线程使用之线程同步synchronized语法结构【附有详细说明及代码】

本文主要是介绍JAVA深化篇_32—— 线程使用之线程同步synchronized语法结构【附有详细说明及代码】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

线程同步

什么是线程同步

同步问题的提出

现实生活中,我们会遇到“同一个资源,多个人都想使用”的问题。 比如:教室里,只有一台电脑,多个人都想使用。天然的解决办法就是,在电脑旁边,大家排队。前一人使用完后,后一人再使用。

线程同步的概念

处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。 这时候,我们就需要用到“线程同步”。 线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕后,下一个线程再使用。

线程冲突案例演示

我们以银行取款经典案例来演示线程冲突现象。

银行取钱的基本流程基本上可以分为如下几个步骤。

(1)用户输入账户、密码,系统判断用户的账户、密码是否匹配。

(2)用户输入取款金额

(3)系统判断账户余额是否大于或等于取款金额

(4)如果余额大于或等于取款金额,则取钱成功;如果余额小于取款金额,则取钱失败。

/*** 账户类*/
class Account{//账号private String accountNo;//账户的余额private double balance;public Account() {}public Account(String accountNo, double balance) {this.accountNo = accountNo;this.balance = balance;}public String getAccountNo() {return accountNo;}public void setAccountNo(String accountNo) {this.accountNo = accountNo;}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}
}
/*** 取款线程*/
class DrawThread implements Runnable{//账户对象private Account account;//取款金额private double drawMoney;public DrawThread(Account account,double drawMoney){this.account = account;this.drawMoney = drawMoney;}/*** 取款线程*/@Overridepublic void run() {//判断当前账户余额是否大于或等于取款金额if(this.account.getBalance() >= this.drawMoney){System.out.println(Thread.currentThread().getName()+" 取钱成功!吐出钞票:"+this.drawMoney);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}//更新账户余额this.account.setBalance(this.account.getBalance()- this.drawMoney);System.out.println("\t 余额为:"+this.account.getBalance());}else{System.out.println(Thread.currentThread().getName()+" 取钱失败,余额不足");}}
}public class TestDrawMoneyThread {public static void main(String[] args) {Account account = new Account("1234",1000);new Thread(new DrawThread(account,800),"老公").start();new Thread(new DrawThread(account,800),"老婆").start();}
}

实现线程同步

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突的问题。Java语言提供了专门机制以解决这种冲突,有效避免了同一个数据对象被多个线程同时访问造成的这种问题。这套机制就是synchronized关键字。

synchronized语法结构:

synchronized(锁对象){   同步代码  
}

synchronized关键字使用时需要考虑的问题:

  • 需要对那部分的代码在执行时具有线程互斥的能力(线程互斥:并行变串行)。
  • 需要对哪些线程中的代码具有互斥能力(通过synchronized锁对象来决定)。

它包括两种用法:

synchronized 方法和 synchronized 块。

  • synchronized 方法

    通过在方法声明中加入 synchronized关键字来声明,语法如下:

public synchronized void accessVal(int newVal);
  • synchronized 在方法声明时使用:放在访问控制符(public)之前或之后。这时同一个对象下synchronized方法在多线程中执行时,该方法是同步的,即一次只能有一个线程进入该方法,其他线程要想在此时调用该方法,只能排队等候,当前线程(就是在synchronized方法内部的线程)执行完该方法后,别的线程才能进入。

  • synchronized块

    synchronized 方法的缺陷:若将一个大的方法声明为synchronized 将会大大影响效率。

    Java 为我们提供了更好的解决办法,那就是 synchronized 块。 块可以让我们精确地控制到具体的“成员变量”,缩小同步的范围,提高效率。

修改线程冲突案例演示

/*** 账户类*/
class Account{//账号private String accountNO;//账户余额private double balance;public Account() {}public Account(String accountNO, double balance) {this.accountNO = accountNO;this.balance = balance;}public String getAccountNO() {return accountNO;}public void setAccountNO(String accountNO) {this.accountNO = accountNO;}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}
}
/*** 取款线程*/
class DrawThread implements Runnable{//账户对象private Account account;//取款金额private double drawMoney;public DrawThread(){}public DrawThread(Account account,double drawMoney){this.account = account;this.drawMoney = drawMoney;}/*** 取款线程体*/@Overridepublic void run() {synchronized (this.account){//判断当前账户余额是否大于或等于取款金额if(this.account.getBalance() >= this.drawMoney){System.out.println(Thread.currentThread().getName()+" 取钱成功!突出钞票"+this.drawMoney);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}//更新账户余额this.account.setBalance(this.account.getBalance() - this.drawMoney);System.out.println("\t 余额为:"+this.account.getBalance());}else{System.out.println(Thread.currentThread().getName()+" 取钱失败,余额不足");}}}
}
public class TestDrawMoneyThread {public static void main(String[] args) {Account account = new Account("1234",1000);new Thread(new DrawThread(account,800),"老公").start();new Thread(new DrawThread(account,800),"老婆").start();}
}

线程同步的使用

使用this作为线程对象锁

语法结构:

synchronized(this){ //同步代码 }

public synchronized void accessVal(int newVal){//同步代码}
/*** 定义程序员类*/
class Programmer{private String name;public Programmer(String name){this.name = name;}/*** 打开电脑*/synchronized public void computer(){try {System.out.println(this.name + " 接通电源");Thread.sleep(500);System.out.println(this.name + " 按开机按键");Thread.sleep(500);System.out.println(this.name + " 系统启动中");Thread.sleep(500);System.out.println(this.name + " 系统启动成功");} catch (InterruptedException e) {e.printStackTrace();}}/*** 编码*/synchronized public void coding(){try {System.out.println(this.name + " 双击Idea");Thread.sleep(500);System.out.println(this.name + " Idea启动完毕");Thread.sleep(500);System.out.println(this.name + " 开开心心的写代码");} catch (InterruptedException e) {e.printStackTrace();}}
}/*** 打开电脑的工作线程*/
class Working1 extends Thread{private Programmer p;public Working1(Programmer p){this.p = p;}@Overridepublic void run() {this.p.computer();}
}/*** 编写代码的工作线程*/
class Working2 extends Thread{private Programmer p;public Working2(Programmer p){this.p = p;}@Overridepublic void run() {this.p.coding();}
}
public class TestSyncThread {public static void main(String[] args) {Programmer p = new Programmer("张三");new Working1(p).start();new Working2(p).start();}
}

使用字符串作为线程对象锁

语法结构:

synchronized(“字符串”){ //同步代码 }
/*** 定义程序员类*/
class Programmer{private String name;public Programmer(String name){this.name = name;}/*** 打开电脑*/synchronized public void computer(){try {System.out.println(this.name + " 接通电源");Thread.sleep(500);System.out.println(this.name + " 按开机按键");Thread.sleep(500);System.out.println(this.name + " 系统启动中");Thread.sleep(500);System.out.println(this.name + " 系统启动成功");} catch (InterruptedException e) {e.printStackTrace();}}/*** 编码*/synchronized public void coding(){try {System.out.println(this.name + " 双击Idea");Thread.sleep(500);System.out.println(this.name + " Idea启动完毕");Thread.sleep(500);System.out.println(this.name + " 开开心心的写代码");} catch (InterruptedException e) {e.printStackTrace();}}/*** 去卫生间*/public void wc(){synchronized ("suibian") {try {System.out.println(this.name + " 打开卫生间门");Thread.sleep(500);System.out.println(this.name + " 开始排泄");Thread.sleep(500);System.out.println(this.name + " 冲水");Thread.sleep(500);System.out.println(this.name + " 离开卫生间");} catch (InterruptedException e) {e.printStackTrace();}}}
}/*** 打开电脑的工作线程*/
class Working1 extends Thread{private Programmer p;public Working1(Programmer p){this.p = p;}@Overridepublic void run() {this.p.computer();}
}/*** 编写代码的工作线程*/
class Working2 extends Thread{private Programmer p;public Working2(Programmer p){this.p = p;}@Overridepublic void run() {this.p.coding();}
}/*** 去卫生间的线程*/
class WC extends Thread{private Programmer p;public WC(Programmer p){this.p = p;}@Overridepublic void run() {this.p.wc();}
}
public class TestSyncThread {public static void main(String[] args) {Programmer p = new Programmer("张三");Programmer p1 = new Programmer("李四");Programmer p2 = new Programmer("王五");new WC(p).start();new WC(p1).start();new WC(p2).start();}
}

用Class作为线程对象锁

语法结构:

synchronized(XX.class){ //同步代码 }

synchronized public static void accessVal()
/*** 定义销售员工类*/
class Sale{private String name;public Sale(String name){this.name = name;}/*** 领取奖金*/synchronized public static void money(){try {System.out.println(Thread.currentThread().getName() + " 被领导表扬");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 拿钱");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 对公司表示感谢");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 开开心心的拿钱走人");} catch (InterruptedException e) {e.printStackTrace();}}
}
class Programmer{private String name;public Programmer(String name){this.name = name;}/*** 打开电脑*/synchronized public void computer(){try {System.out.println(this.name + " 接通电源");Thread.sleep(500);System.out.println(this.name + " 按开机按键");Thread.sleep(500);System.out.println(this.name + " 系统启动中");Thread.sleep(500);System.out.println(this.name + " 系统启动成功");} catch (InterruptedException e) {e.printStackTrace();}}/*** 编码*/synchronized public void coding(){try {System.out.println(this.name + " 双击Idea");Thread.sleep(500);System.out.println(this.name + " Idea启动完毕");Thread.sleep(500);System.out.println(this.name + " 开开心心的写代码");} catch (InterruptedException e) {e.printStackTrace();}}/*** 去卫生间*/public void wc(){synchronized ("suibian") {try {System.out.println(this.name + " 打开卫生间门");Thread.sleep(500);System.out.println(this.name + " 开始排泄");Thread.sleep(500);System.out.println(this.name + " 冲水");Thread.sleep(500);System.out.println(this.name + " 离开卫生间");} catch (InterruptedException e) {e.printStackTrace();}}}/*** 领取奖金*/public void money(){synchronized (Programmer.class) {try {System.out.println(this.name + " 被领导表扬");Thread.sleep(500);System.out.println(this.name + " 拿钱");Thread.sleep(500);System.out.println(this.name + " 对公司表示感谢");Thread.sleep(500);System.out.println(this.name + " 开开心心的拿钱走人");} catch (InterruptedException e) {e.printStackTrace();}}}
}/*** 打开电脑的工作线程*/
class Working1 extends Thread{private Programmer p;public Working1(Programmer p){this.p = p;}@Overridepublic void run() {this.p.computer();}
}/*** 编写代码的工作线程*/
class Working2 extends Thread{private Programmer p;public Working2(Programmer p){this.p = p;}@Overridepublic void run() {this.p.coding();}
}/*** 去卫生间的线程*/
class WC extends Thread{private Programmer p;public WC(Programmer p){this.p = p;}@Overridepublic void run() {this.p.wc();}
}/*** 程序员领取奖金*/
class ProgrammerMoney extends Thread{private Programmer p;public ProgrammerMoney(Programmer p){this.p = p;}@Overridepublic void run() {this.p.money();}
}/*** 销售部门领取奖金*/
class SaleMoney extends Thread{private Sale p;public SaleMoneyThread(Sale p){this.p = p;}@Overridepublic void run() {this.p.money();}
}public class TestSyncThread {public static void main(String[] args) {/*  Programmer p = new Programmer("张三");Programmer p1 = new Programmer("李四");new ProgrammerMoney(p).start();new ProgrammerMoney(p1).start();*/Sale s = new Sale("张晓丽");Sale s1 = new Sale("王晓红");new SaleMoney(s).start();new SaleMoney(s1).start();}
}

使用自定义对象作为线程对象锁

语法结构:

synchronized(自定义对象){ //同步代码 
}
/*** 定义销售员工类*/
class Sale{private String name;public Sale(String name){this.name = name;}/*** 领取奖金*/synchronized public static void money(){try {System.out.println(Thread.currentThread().getName() + " 被领导表扬");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 拿钱");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 对公司表示感谢");Thread.sleep(500);System.out.println(Thread.currentThread().getName() + " 开开心心的拿钱走人");} catch (InterruptedException e) {e.printStackTrace();}}
}
class Programmer{private String name;public Programmer(String name){this.name = name;}/*** 打开电脑*/synchronized public void computer(){try {System.out.println(this.name + " 接通电源");Thread.sleep(500);System.out.println(this.name + " 按开机按键");Thread.sleep(500);System.out.println(this.name + " 系统启动中");Thread.sleep(500);System.out.println(this.name + " 系统启动成功");} catch (InterruptedException e) {e.printStackTrace();}}/*** 编码*/synchronized public void coding(){try {System.out.println(this.name + " 双击Idea");Thread.sleep(500);System.out.println(this.name + " Idea启动完毕");Thread.sleep(500);System.out.println(this.name + " 开开心心的写代码");} catch (InterruptedException e) {e.printStackTrace();}}/*** 去卫生间*/public void wc(){synchronized ("suibian") {try {System.out.println(this.name + " 打开卫生间门");Thread.sleep(500);System.out.println(this.name + " 开始排泄");Thread.sleep(500);System.out.println(this.name + " 冲水");Thread.sleep(500);System.out.println(this.name + " 离开卫生间");} catch (InterruptedException e) {e.printStackTrace();}}}/*** 领取奖金*/public void money(){synchronized (Programmer.class) {try {System.out.println(this.name + " 被领导表扬");Thread.sleep(500);System.out.println(this.name + " 拿钱");Thread.sleep(500);System.out.println(this.name + " 对公司表示感谢");Thread.sleep(500);System.out.println(this.name + " 开开心心的拿钱走人");} catch (InterruptedException e) {e.printStackTrace();}}}
}
class Manager{private String name;public Manager(String name){this.name = name;}public String getName(){return this.name;}/*** 敬酒*/public void cheers(String mName,String eName){try {System.out.println(mName + " 来到 " + eName + " 面前");Thread.sleep(500);System.out.println(eName + " 拿起酒杯");Thread.sleep(500);System.out.println(mName + " 和 " + eName + " 干杯");} catch (InterruptedException e) {e.printStackTrace();}}
}
/*** 打开电脑的工作线程*/
class Working1 extends Thread{private Programmer p;public Working1(Programmer p){this.p = p;}@Overridepublic void run() {this.p.computer();}
}/*** 编写代码的工作线程*/
class Working2 extends Thread{private Programmer p;public Working2(Programmer p){this.p = p;}@Overridepublic void run() {this.p.coding();}
}/*** 去卫生间的线程*/
class WC extends Thread{private Programmer p;public WC(Programmer p){this.p = p;}@Overridepublic void run() {this.p.wc();}
}/*** 程序员领取奖金*/
class ProgrammerMoney extends Thread{private Programmer p;public ProgrammerMoney(Programmer p){this.p = p;}@Overridepublic void run() {this.p.money();}
}/*** 销售部门领取奖金*/
class SaleMoneyThread extends Thread{private Sale p;public SaleMoneyThread(Sale p){this.p = p;}@Overridepublic void run() {this.p.money();}
}/*** 敬酒线程类*/
class CheersThread extends Thread{private Manager manager;private String name;public CheersThread(String name,Manager manager){this.name = name;this.manager = manager;}@Overridepublic void run() {synchronized (this.manager) {this.manager.cheers(this.manager.getName(), name);}}
}public class TestSyncThread {public static void main(String[] args) {Manager manager = new Manager("张三丰");new CheersThread("张三",manager).start();new CheersThread("李四",manager).start();}
}

死锁及解决方案

死锁的概念

“死锁”指的是:

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能进行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。

某一个同步块需要同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。比如,“化妆线程”需要同时拥有“镜子对象”、“口红对象”才能运行同步块。那么,实际运行时,“小丫的化妆线程”拥有了“镜子对象”,“大丫的化妆线程”拥有了“口红对象”,都在互相等待对方释放资源,才能化妆。这样,两个线程就形成了互相等待,无法继续运行的“死锁状态”。

死锁案例演示

/*** 口红类*/
class Lipstick{}/*** 镜子类*/
class Mirror{}/*** 化妆线程类*/
class Makeup extends Thread{private int flag; //flag=0:拿着口红。flag!=0:拿着镜子private String girlName;static Lipstick lipstick = new Lipstick();static Mirror mirror = new Mirror();public Makeup(int flag,String girlName){this.flag = flag;this.girlName = girlName;}@Overridepublic void run() {this.doMakeup();}/*** 开始化妆*/public void doMakeup(){if(flag == 0){synchronized (lipstick){System.out.println(this.girlName+" 拿着口红");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}synchronized (mirror){System.out.println(this.girlName+" 拿着镜子");}}}else{synchronized (mirror){System.out.println(this.girlName+" 拿着镜子");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}synchronized (lipstick){System.out.println(this.girlName+" 拿着口红");}}}}
}public class DeadLockThread {public static void main(String[] args) {new Makeup(0,"大丫").start();new Makeup(1,"小丫").start();}
}

死锁问题的解决

死锁是由于 “同步块需要同时持有多个对象锁造成”的,要解决这个问题,思路很简单,就是:同一个代码块,不要同时持有两个对象锁。

/*** 口红类*/
class Lipstick{}/*** 镜子类*/
class Mirror{}/*** 化妆线程类*/
class Makeup extends Thread{private int flag; //flag=0:拿着口红。flag!=0:拿着镜子private String girlName;static Lipstick lipstick = new Lipstick();static Mirror mirror = new Mirror();public void setFlag(int flag) {this.flag = flag;}public void setGirlName(String girlName) {this.girlName = girlName;}@Overridepublic void run() {this.doMakeup();}/*** 开始化妆*/public void doMakeup(){if(flag == 0){synchronized (lipstick){System.out.println(this.girlName+" 拿着口红");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}synchronized (mirror){System.out.println(this.girlName+" 拿着镜子");}}else{synchronized (mirror){System.out.println(this.girlName+" 拿着镜子");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}synchronized (lipstick){System.out.println(this.girlName+" 拿着口红");}}}
}public class DeadLockThread {public static void main(String[] args) {Makeup makeup = new Makeup();makeup.setFlag(0);makeup.setGirlName("大丫");Makeup makeup1 = new Makeup();makeup1.setFlag(1);makeup1.setGirlName("小丫");makeup.start();makeup1.start();}
}

这篇关于JAVA深化篇_32—— 线程使用之线程同步synchronized语法结构【附有详细说明及代码】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/352079

相关文章

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja