多线程安全问题
多线程安全问题为什么会出现:
因为程序在运行时,会出现一个线程在判断条件满足后,但没有运行代码。但是后一个线程也判断了条件,也具备了执行了资格,后一个线程运行了代码,但这时候线程运行的条件不满足了,便出现了安全问题。多线程出现安全问题的原因:
当多条语句在操作同一线程共享数据时,一个线程对多条语句执行了一部分,还没有执行完,另一个线程参与进来,导致共享数据错误。解决方法:
对多条操作共享数据的语句,只能让一个线程都执行完。在执行过程中,其他线程不参与执行。
同步代码块
为了解决并发操作问题可能造成的异常,Java多线程支持引入了同步监视器来解决这个问题,即同步代码块。
synchronized(obj){
//同步代码块
}
obj就是同步监视器,它的含义是:线程开始执行同步代码块之前,必须先获得对同步监视器的锁定。任何时刻只能有一个线程可以获得对同步监视器的锁定,当同步代码块执行完成后,该线程会释放对改同步监视器的锁定。
通常推荐使用可能被并发访问的共享资源充当同步监视器
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;
}
@Override
public int hashCode() {
return accountNo.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj!=null&&obj.getClass()==Account.class){
Account target=(Account)obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}
class DrawThread extends Thread{
private Account account;
//所希望取得钱数
private double drawAmount;
public DrawThread(String name,Account account,double drawAmount){
super(name);
this.account=account;
this.drawAmount=drawAmount;
}
public void run(){
synchronized(account){
//使用并发访问的共享资源account作为同步监视器
if(account.getBalance()>=drawAmount){
System.out.println(this.getName()+"取钱成功,吐出钞票"+drawAmount);
try{
Thread.sleep(1);
}catch(InterruptedException ex){
ex.printStackTrace();
}
account.setBalance(account.getBalance()-drawAmount);
System.out.println("\t余额为:"+account.getBalance());
}
else{
System.out.println(this.getName()+"取钱失败!越余额不足");
}
}
//同步代码块结束该线程释放该锁
}
}
public class DrawTest{
public static void main(String[] args) {
Account acct=new Account("123456",1000);
new DrawThread("甲",acct,800).start();
new DrawThread("乙",acct,800).start();
}
}
上面同步代码块符合“加锁->修改->释放锁”的逻辑
隐式定义锁
同步方法
同步方法就是使用synchronized关键字来修饰某个方法,则该方法称为同步方法。对于synchronized修饰的实例方法(非static)方法而言,无需显示指定同步监视器,同步方法的监视器是this,也就是调用该方法的对象。
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;
}
public synchronized void draw(double drawAmount){
if(balance>=drawAmount){
System.out.println(Thread.currentThread().getName()+"取钱成功,吐出钞票"+drawAmount);
try{
Thread.sleep(1);
}catch(InterruptedException ex){
ex.printStackTrace();
}
balance-=drawAmount;
System.out.println("\t余额为:"+balance);
}
else{
System.out.println(Thread.currentThread().getName()+"取钱失败!越余额不足");
}
}
@Override
public int hashCode() {
return accountNo.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj!=null&&obj.getClass()==Account.class){
Account target=(Account)obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}
class DrawThread extends Thread{
private Account account;
//所希望取得钱数
private double drawAmount;
public DrawThread(String name,Account account,double drawAmount){
super(name);
this.account=account;
this.drawAmount=drawAmount;
}
public void run(){
account.draw(drawAmount);
}
}
public class DrawTest{
public static void main(String[] args) {
Account acct=new Account("123456",1000);
new DrawThread("甲",acct,800).start();
new DrawThread("乙",acct,800).start();
}
}
隐式定义锁
同步锁
从Java5开始,Java提供了一种功能更强大的线程同步机制——通过显式定义同步锁对象来实现同步,在这种机制下,同步锁由Lock对象充当。
Lock 对象提供了比synchronized方法和synchronized代码块更广泛的锁定操作,Lock是控制多个线程对共享资源进行访问的工具。通常, 锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应该先获得Lock对象。
> 在实现线程安全的控制中,比较常用的是ReentrantLock(可重入锁)。主要的代码格式如下:
class X{
private final ReenrantLock lock=new ReenrantLock();
public void m(){
lock.lock();
try{
//需要保证线程安全的代码块
}
finally{
lock.unlock();
}
}
}
在使用ReentranLock对象来进行同步时,可以把Account类修改为如下:
class Account {
private final ReentrantLock lock=new ReentrantLock();
//封装账户编号 账户余额两个成员变量
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;
}
public void draw(double drawAmount){
lock.lock();
try{
if(balance>=drawAmount){
System.out.println(Thread.currentThread().getName()+"取钱成功,吐出钞票"+drawAmount);
try{
Thread.sleep(1);
}catch(InterruptedException ex){
ex.printStackTrace();
}
balance-=drawAmount;
System.out.println("\t余额为:"+balance);
}
else{
System.out.println(Thread.currentThread().getName()+"取钱失败!越余额不足");
}
}
finally{
lock.unlock();
}
}
@Override
public int hashCode() {
return accountNo.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj!=null&&obj.getClass()==Account.class){
Account target=(Account)obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}