码迷,mamicode.com
首页 > 其他好文 > 详细

sychronized

时间:2016-02-01 13:56:53      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

 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();
    }
}

 

sychronized

标签:

原文地址:http://www.cnblogs.com/barker/p/5174526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!