問題分析:正如i在多線程中若是想實現i的多線程操做,必須i要使用volitle來保證其內存可見性,可是i++自增操做不具有原子性操做,所以須要對i++這段代碼確保其原子性操做便可。多線程
使用ReetranLock實現i++的原子性操做。ide
private static volatile int i=0; public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch=new CountDownLatch(2); Lock lock=new ReentrantLock(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try{ lock.lock(); i++; }finally{ lock.unlock(); countDownLatch.countDown(); } } },"Thread-1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try{ lock.lock(); i++; }finally{ lock.unlock(); countDownLatch.countDown(); } } },"Thread-2"); thread1.start(); thread2.start(); countDownLatch.await(); System.out.println(i); }
使用Semaphore實現i++的原子性操做。ui
private static volatile int i = 0; public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); Semaphore semaphore = new Semaphore(1); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } i++; semaphore.release(); countDownLatch.countDown(); } }, "Thread-1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } i++; semaphore.release(); countDownLatch.countDown(); } }, "Thread-2"); thread1.start(); thread2.start(); countDownLatch.await(); System.out.println(i); }
固然也能夠選擇sychronized方式實現。spa