首页 > 其他 > 详细

2.8.4 错误的加锁

时间:2018-02-07 11:08:11      阅读:175      评论:0      收藏:0      [点我收藏+]
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 错误的加锁

原文:https://www.cnblogs.com/anxbb/p/8425479.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!