package 第二章.错误的加锁;
/**
* Created by zzq on 2018/1/22.
*/
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()
*/
/**
* 得到的结果并不是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);
}
public void run() {
for (int j = 0; j < 1000000; j++) {
synchronized (instance) {//这里同步的并不是同一个对象,因为i是以Integer关键字创建的
//正确做法应该是 synchronized (instance)
i++;
}
}
}
}
2.8.4 错误的加锁
Posted anxbb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.8.4 错误的加锁相关的知识,希望对你有一定的参考价值。
以上是关于2.8.4 错误的加锁的主要内容,如果未能解决你的问题,请参考以下文章
JDK源码笔记之Integer深度解析以及并发下错误的加锁方式踩坑笔记