一、同步机制存在的问题
1、死锁
2、即使只有一个线程访问这个对象,仍然需要执行必须的代码来获取和释放锁
二、Compare-and-Swap-Operation
1、取得变量值,即变量的旧值
2、在一个临时变量中修改变量值,即变量的新值
3、如果上面获得的变量旧值与当前变量值相等,就用新值替换旧值。如果已有其他线程修改了这个变量的值,上面获得的变量的旧值就可能与当前变量值不同
三、原子数组
package concurrencycollection; import java.util.concurrent.atomic.AtomicIntegerArray; public class Incrementer implements Runnable { private AtomicIntegerArray atomicIntegerArray; public Incrementer(AtomicIntegerArray atomicIntegerArray) { this.atomicIntegerArray = atomicIntegerArray; } @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < atomicIntegerArray.length(); i++) { atomicIntegerArray.getAndIncrement(i); } } }
package concurrencycollection; import java.util.concurrent.atomic.AtomicIntegerArray; public class Decrementer implements Runnable { private AtomicIntegerArray atomicIntegerArray; public Decrementer(AtomicIntegerArray atomicIntegerArray) { this.atomicIntegerArray = atomicIntegerArray; } @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < atomicIntegerArray.length(); i++) { atomicIntegerArray.getAndDecrement(i); } } }
package concurrencycollection; import java.util.concurrent.atomic.AtomicIntegerArray; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000); final int THREADS = 100; Incrementer incrementer = new Incrementer(atomicIntegerArray); Decrementer decrementer = new Decrementer(atomicIntegerArray); Thread[] threadsIncrementer = new Thread[THREADS]; Thread[] threadsDecrementer = new Thread[THREADS]; for (int i = 0; i < THREADS; i++) { threadsIncrementer[i] = new Thread(incrementer); threadsDecrementer[i] = new Thread(decrementer); threadsIncrementer[i].start(); threadsDecrementer[i].start(); } for (int i = 0; i < 100; i++) { try { threadsIncrementer[i].join(); threadsDecrementer[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < atomicIntegerArray.length(); i++) { if (atomicIntegerArray.get(i) != 0) { System.out.println("Vector[" + i + "] : " + atomicIntegerArray.get(i)); } } System.out.println("Main : End of the example"); } }