码迷,mamicode.com
首页 > 其他好文 > 详细

2.8.4 错误的加锁

时间:2018-02-07 12:10:14      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:ram   线程   关键字   错误   start   同步   pre   bad   package   

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 错误的加锁

标签:ram   线程   关键字   错误   start   同步   pre   bad   package   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!