多线程访问同一个变量,不进行同步,会造成结果不一致。这里解决方案有很多,使用原子变量。加锁同步,使用synchronized同步。下面是一个lock demo,后面会分析lock实现原理。lock使用的是公平锁还是非公平锁等
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;/*** Created by GuanXF on 2017/11/26.*/ public class TestLock {private static Lock lock = new ReentrantLock();private static int count = 0 ; // private static AtomicInteger count = new AtomicInteger(0);public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(task);Thread t2 = new Thread(task1);t1.start();t2.start();t1.join();t2.join();System.out.println("count = " + count);}static Runnable task1 = new Runnable() {@Overridepublic void run() {int index = 10000;while(index > 0){lock.lock();count++;lock.unlock(); // count.incrementAndGet();index --;}}};static Runnable task = new Runnable() {@Overridepublic void run() {int index = 10000;while(index > 0){lock.lock();count++;lock.unlock(); // count.incrementAndGet();index --;}}}; }