码迷,mamicode.com
首页 > 编程语言 > 详细

Java并发之synchronized

时间:2018-04-07 01:10:49      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:synchronized

synchronized关键字最主要有以下3种应用方式

修饰实例方法,作用于当前实例加锁,进入同步代码前要获得当前实例的锁;实例锁,一个实例一把锁

修饰静态方法,作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁;对象锁,一个对象一把锁

修饰代码块,指定加锁对象,对给定对象加锁,进入同步代码库前要获得给定对象的锁;对象锁,一个对象一把锁

实例锁
public class SuperHakceTest implements Runnable{

    public static Integer flag = 0;

    public synchronized void instanse(){
        flag ++;
    }

    @Override
    public void run() {
        for(int i = 0;i < 1000;i ++){
            instanse();
        }
    }

    public static void main(String[] args) throws Exception{
        SuperHakceTest superHakceTest = new SuperHakceTest();
        Thread thread1 = new Thread(superHakceTest);
        Thread thread2 = new Thread(superHakceTest);
        Thread thread3 = new Thread(superHakceTest);
        thread1.start();thread2.start();thread3.start();
        thread1.join();thread2.join();thread3.join();
        System.out.println("LAST FLAG = " + SuperHakceTest.flag);
    }

}

对象锁
public class SuperHakceTest implements Runnable{

    public static Integer flag = 0;

    public static synchronized void instanse(){
        flag ++;
    }

    @Override
    public void run() {
        for(int i = 0;i < 1000;i ++){
            instanse();
        }
    }

    public static void main(String[] args) throws Exception{
        SuperHakceTest superHakceTest1 = new SuperHakceTest();
        SuperHakceTest superHakceTest2 = new SuperHakceTest();
        SuperHakceTest superHakceTest3 = new SuperHakceTest();
        Thread thread1 = new Thread(superHakceTest1);
        Thread thread2 = new Thread(superHakceTest2);
        Thread thread3 = new Thread(superHakceTest3);
        thread1.start();thread2.start();thread3.start();
        thread1.join();thread2.join();thread3.join();
        System.out.println("LAST FLAG = " + SuperHakceTest.flag);
    }

}

//this,当前实例对象锁
synchronized(this){
    for(int j=0;j<1000000;j++){
        i++;
    }
}

//class对象锁
synchronized(AccountingSync.class){
    for(int j=0;j<1000000;j++){
        i++;
    }
}

Java并发之synchronized

标签:synchronized

原文地址:http://blog.51cto.com/superhakce/2095308

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