我写了一个测试,开启10个线程,同时对一个数据进行10w次递增,使用synchronized进行加锁,但是使用lambda和未使用两种情况缺得出了不一样的结果
定义了一个静态int变量
static Integer value2 = 0;这是使用lambda的情况,得出正确的结果
public void testaa() throws InterruptedException { int threadSize = 10; Thread[] ts = new Thread[threadSize]; for (int i = 0; i < threadSize; i++) { ts[i] = new Thread( ()-> { for (int j = 0; j < 100000; j++) { synchronized (this) { value2++; } } }); // } for (Thread t : ts) { t.start(); } for (Thread t : ts) { t.join(); }}而未使用lambda表达式怎样都运算错误
public void testaa() throws InterruptedException { int threadSize = 10; Thread[] ts = new Thread[threadSize]; for (int i = 0; i < threadSize; i++) { ts[i] = new Thread() { public void run() { for (int j = 0; j < 100000; j++) { synchronized (this) { value2++; } } } }; // } for (Thread t : ts) { t.start(); } for (Thread t : ts) { t.join(); } System.out.println(value2);}希望有人能帮我解答一下!!!谢谢