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);

    }
}

你可能感兴趣的:(java多线程)