1 Star 0 Fork 24

ICY/concurrent-programming

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BadLockOnInteger.java 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
ZHENFENGSHISAN 提交于 2017-05-04 16:09 +08:00 . BadLockOnInteger
package chapter2;
/**
* 这是一个错误的加锁方式
* <p/>
* Created by 13 on 2017/5/4.
*/
public class BadLockOnInteger implements Runnable {
public static Integer i = 0;
static BadLockOnInteger instance = new BadLockOnInteger();
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p/>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
synchronized (i) {//这里同步的并不是同一个对象,因为i是以Integer关键字创建的
//正确做法应该是 synchronized (instance)
i++;
}
}
}
/**
* 得到的结果并不是2000000,在多线程的操作中出现了错误
*
* @param args
* @throws InterruptedException
*/
public static void main(String args[]) throws InterruptedException {
Thread thread1 = new Thread(instance);
Thread thread2 = new Thread(instance);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(i);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/javaIcy/concurrent-programming.git
git@gitee.com:javaIcy/concurrent-programming.git
javaIcy
concurrent-programming
concurrent-programming
master

搜索帮助