java 多线程同步方法的实现

同步方法:在方法声明上加上synchronized

public synchronized void method(){

   可能会产生线程安全问题的代码

}

同步方法中的锁对象是 this

使用同步方法,对电影院卖票案例中Ticket类进行如下代码修改:

public class Ticket implements Runnable {
    //共100票
    int ticket = 100;
    public void run() {
        //模拟卖票
        while(true){
            //同步方法
            method();
        }
    }

//同步方法,锁对象this
    public synchronized void method(){
        if (ticket > 0) {
            //模拟选坐的操作
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在卖票:" + ticket--);
        }
    }
}

但是在静态同步方法中,也就是:

public static synchronized void method(){
可能会产生线程安全问题的代码
}

锁不是this而是 类名.class 。静态方法中没有this。

 

posted on 2017-11-23 22:48 星辰的零落 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/xiaoyu233/p/7887450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值