package cn.com.zxf.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample implements Runnable{
private AtomicInteger atomicInteger;
private int index;
public AtomicExample(AtomicInteger atomicInteger, int index){
this.atomicInteger=atomicInteger;
this.index = index;
}
@Override
public void run() {
System.out.println("当前线程名称:"+Thread.currentThread().getName());
atomicInteger.addAndGet(index);
}
}
cn.com.zxf.atomic Package Penalty for;
Import java.util.concurrent *;.
Import java.util.concurrent.atomic.AtomicInteger;
Import java.util.concurrent.locks.Lock;
Import java.util.concurrent.locks.ReentrantLock ;
public class AtomicExampleTest {
// thread pool
Private static ExecutorService ExecutorService = Executors.newFixedThreadPool (10);
public static void main (String [] args) throws Exception {
// Shan stopped using
a CountDownLatch CountDownLatch a CountDownLatch new new = (100);
// semaphore
semaphore semaphore semaphore new new = (. 3);
// Atomic packet is based on the use of the underlying CAS concurrent programming
final AtomicInteger atomicInteger = new AtomicInteger () ;
lock // java provided
Lock lock = new ReentrantLock();
//队列
LinkedBlockingDeque linkedBlockingDeque = new LinkedBlockingDeque();
for(int i = 0 ;i<100; i++){
Thread.sleep(1000);
semaphore.acquire();
executorService.execute(new AtomicExample(atomicInteger,1));
semaphore.release();
Thread.sleep(1000);
countDownLatch.countDown();
}
countDownLatch.await();
executorService.shutdown();
System.out.println("计算值:"+atomicInteger.get());
}
}
concurrent use