sychronized

 Java提供了强制原子性的内置锁机制:synchronized块。一个synchronized块有两部分:锁对象的引用(作为锁的对象一定要是final的,保证锁对象不会被重新赋值),以及这个锁保护的代码块。

public class Example5 {
    
    final static Object lock = new Object();
    static int num = 0;
    
    public void add(){
        synchronized (lock) {
            num++;
        }            
    }
}

 synchronized方法是对跨越了整个方法体的synchronized块的简短描述,至于synchronized方法的锁,就是该方法所在的对象本身。(静态的synchronized方法从Class对象上获取锁)

public class Example5 {
    
    static int num = 0;
    
    public synchronized void add(){
        num++;
    }
}

public class Example5 {

    static int num = 0;

    public void add(){
        synchronized (this) {
            num++;
        }
    }
}

 

静态sychronized方法

public class Example5 {

    static int num = 0;

    public void opt1(){
        synchronized (Example5.class) {
            num++;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            num--;
            System.out.println("线程:"+Thread.currentThread().getId()+",num:"+num);
        }
    }
    
    //opt2与opt1效果相同
    public static synchronized void opt2(){
        num++;
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num--;
        System.out.println("线程:"+Thread.currentThread().getId()+",num:"+num);
    }
    
    public static void main(String[] args){
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                Example5 example5 = new Example5();
                for (int i = 0; i < 100; i++) {
                    example5.opt1();
                }
            }
        }).start();
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    Example5.opt2();
                }
            }
        }).start();
    }
}

 

posted @ 2016-02-01 09:53  PaganMonkey  阅读(250)  评论(0编辑  收藏  举报

喜欢的话可以打赏一下哦!!!

支付宝

微信