专注java. 2022-03-30 22:07 采纳率: 95%
浏览 54
已结题

java synchronized(this)同步代码块括号里面的this为什么不能实现线程同步(具体问题在下面代码后面的粗体的注释)

package com.bjpowernode.java.threadsafe2;

public class Test {
public static void main(String[] args) {
Account act = new Account("act-001", 10000);
Thread t1 = new AccountThread(act);
Thread t2 = new AccountThread(act);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class Account {
private String actno;
private double balance;
public Account() {
}
public Account(String actno, double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double money) {
synchronized (this){//这里的this和下面(AccountThread线程类中同步代码块)的this有什么区别
double before = this.getBalance();
double after = before - money;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {**
e.printStackTrace();
}
this.setBalance(after);
}
}
}
class AccountThread extends Thread {
private Account act;
public AccountThread(Account act) {
this.act = act;
}
public void run(){
double money = 5000;
synchronized (this) {//这里的this为什么不能实现同步机制,
act.withdraw(money);
}
System.out.println(Thread.currentThread().getName() + "对"+act.getActno()+"取款"+money+"成功,余额" + act.getBalance());
}
}

  • 写回答

2条回答 默认 最新

  • Tomshidi 2022-03-30 22:19
    关注

    this代表的是当前实例对象,假设你有一百个线程,那每个AccountThread实例对象里的this都是新的。
    synchronized能锁住线程的前提是多个线程争抢同一个对象上的锁,你这this全都不同,锁了个寂寞,每个线程都自给自足,当然就全部同时执行了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月8日
  • 已采纳回答 3月31日
  • 创建了问题 3月30日

悬赏问题

  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能