java lock
多線程訪問同一個變量,不進行同步,會造成結果不一致。這里解決方案有很多,使用原子變量。加鎖同步,使用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 --;}}}; }?
轉載于:https://www.cnblogs.com/luckygxf/p/7900788.html
總結
- 上一篇: 安卓手机字体替换教程?
- 下一篇: nodejs面试题