synchronous錯誤使用

i++後對象變化了,所以會出現錯誤的結果。

package com.brendan.cn.concurrent;

import java.net.InetAddress;

/***************************************************************
 * Created by martin on 2017/9/29.
 ***************************************************************/
public class IntegerLock {

    static Integer i = 0;

    public  static  class  AddThread extends Thread {
        @Override
        public void run() {
            for(int k=0;k<10000;k++){
                synchronized (i) {
                    i++;
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new AddThread();
        Thread t2 = new AddThread();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章