博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java并发之synchronized
阅读量:6984 次
发布时间:2019-06-27

本文共 1958 字,大约阅读时间需要 6 分钟。

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++;    }}

转载于:https://blog.51cto.com/superhakce/2095308

你可能感兴趣的文章
eclipse
查看>>
angularjs定时任务的设置与清除
查看>>
C#获取文件的MD5值
查看>>
字符串子串查找strstr
查看>>
个人Vue-1.0学习笔记
查看>>
string的属性小试
查看>>
JS中3种弹出窗口函数区别分析
查看>>
《深入理解计算机系统》 优化程序性能的几个方法
查看>>
WPF项目中使用水晶报表for vs2010时的一个找不到程序集的问题
查看>>
关于C/C++的一些思考(2)
查看>>
相对导入中Attempted relative import in non-package问题
查看>>
【前行】◇第3站◇ 国庆训练营·OI制模拟赛
查看>>
python —— I/O
查看>>
hive计算周一的日期
查看>>
梦断代码读后感(二)
查看>>
接口测试(1)
查看>>
mongodb副本集的docker化安装
查看>>
基于位运算的权限控制
查看>>
概率DP
查看>>
邻接表——最简单易懂的写法——向非我非非我大佬低头
查看>>