synchronized问题

问题遇到的现象和发生背景

请问一下这段代码加了synchronized为啥还会抢线程呢?

用代码块功能插入代码,请勿粘贴截图

public class Site implements Runnable {
private int count = 10;
private int num =0;
private boolean flag=false;

public void run() {
    while (!flag) {
        sale();
    }
}


public synchronized void sale() {
    if (count<=0) {
        flag = true; 
        return;
    }
    count--;
    num++;
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"获得"+num+"张票"+"剩余"+count);
}


public static void main(String[] args) {
    Thread thd = new Thread(new Site(),"张三");
    Thread thd1 = new Thread(new Site(),"李四");
    Thread thd2 = new Thread(new Site(),"王五");
    
    thd.start();
    thd1.start();
    thd2.start();
}

}

运行结果及报错内容

还是会抢线程,明明加了synchronized了

这种方法是不是new 了三个Site(),导致锁不唯一。
给这个方法用static修饰一下,即public static synchronized
让这个线程🔒为Site.class,另外,你这线程操作的变量也要是静态的,要共享呀,num和count也用static修饰。
建议是你直接创建一个Site,这样就不用做任何修改,本质上是对多线程理解不够深入。
有帮助的话采纳一下哦!

因为你的 Site 类,三个不同的线程 new 了 三个不同的实例, 而关键字 synchronized 是加在 site的方法上的, 实例都不一样,所以 不会同步,各自执行各自的。
改成这样即可:

img


如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!