1. 程式人生 > >2.8.4 錯誤的加鎖

2.8.4 錯誤的加鎖

rup args 多線程 clas print 加鎖 cal row integer

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 錯誤的加鎖