JAVA中多线程的同步方法和静态同步方法

接 https://blog.csdn.net/godkzz/article/details/119390742?spm=1001.2014.3001.5501

一、同步方法

线程安全问题除了同步代码块,还可以用同步方法解决

public class RunnableImpl implements Runnable {

    private int ticket = 100;
    @Override
    public void run() {
        while (true)
        {
            sell();
        }
    }

    public synchronized void sell(){//加上同步方法关键字
        if (this.ticket > 0)
        {
            System.out.println(Thread.currentThread().getName()+"正在卖第"+ ticket-- +"张票");
        }
    }
}
public class Main {
    public static void main(String[] args) {
        RunnableImpl r = new RunnableImpl();
        Thread thread1 = new Thread(r);
        Thread thread2 = new Thread(r);
        Thread thread3 = new Thread(r);
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

另外:同步方法的锁对象,就是对象本身,在这里就是RunnableImpl也就是this!

 二、静态同步方法

静态同步方法,只需要给同步方法加上静态关键字以及给操作的变量加上静态关键字即可

public class RunnableImpl implements Runnable {

    private static int ticket = 100;//操作的变量需要静态!
    @Override
    public void run() {
        while (true)
        {
            sell();
        }
    }

    public static synchronized void sell(){//加上同步方法关键字 以及 静态关键字
        if (ticket > 0)
        {
            System.out.println(Thread.currentThread().getName()+"正在卖第"+ ticket-- +"张票");
        }
    }
}

另外:静态同步方法的锁与同步方法的锁对象不一样!

同步方法的锁对象为this,但this是对象创建后才产生的。

对象中方法的创建顺序应该为:父类静态代码块/父类静态成员变量–>子类静态代码块/子类静态成员变量–>父类普通代码块/父类普通成员变量–>父类的构造方法–>子类普通代码块/子类普通成员变量–>子类的构造方法。

静态方法的锁对象是本来的class属性:class文件对象(反射)

例如在本案例中 静态同步方法锁的对象应为:Class.forname("com.demo.RunnableImpl")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值