星辰的零落

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

同步方法:在方法声明上加上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  星辰的零落  阅读(215)  评论(0编辑  收藏  举报