synchronized
来源:互联网 发布:盘锦中小企业seo 编辑:程序博客网 时间:2024/06/17 17:42
synchronized void t(){}void t2(){synchronized(this){}}
这两种也是等效的
static synchronized void t(){}static void t1(){synchronized(Run1.class){}}
例1:
public class Sync {static int num=0;public static void main(String[] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool();executorService.execute(new Run1());executorService.execute(new Run1());executorService.execute(new Run1());executorService.execute(new Run1());Thread.sleep(100);System.out.println(num);}static class Run1 implements Runnable{@Overridepublic void run() {t();}void t(){for(int i=0;i<100000;i++){synchronized(this){num++;}}}}}
输出随机 小于40w
因为 线程执行的是不同的对象 所以互补干扰
修改代码
将 synchronized(this) 改为 synchronized(this.getClass())
这样输出 就为40w
或者 将线程池去执行同一个Runnable实例 这样 执行结果也是40w
Run1 r = new Run1();executorService.execute(r);executorService.execute(r);executorService.execute(r);executorService.execute(r);
阅读全文
0 0
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- AI | 刘强东谈京东AI布局:春节后重型无人机上飞测试 载重过吨
- 揭秘深圳智能音箱地下江湖 千家小厂命悬一线!
- 图解Javascript this指向什么
- Event的简单实现登录相互传递数据
- 常用权限和依赖
- synchronized
- MFC写的一个ping程序
- Atlas的安装配置及MySQL主从复制配置,两者连接使用
- python: reverse & reversed 函数
- 正则应用之切分数字及文本
- 解决Eclipse的web项目中右击没有browse deployment location选项
- java 日期类总结
- 牛客网---2016---楚楚街礼物
- 回归分析之Sklearn实现电力预测