volatile
若不用volatile关键字,这个域就只能用同步来访问,因为同步也会向主存刷新。
AtomicInteger、Long、etc
int java.util.concurrent.atomic.AtomicInteger.incrementAndGet()
原子性的给当前值加上1
Atomically increments by one the current value.
int java.util.concurrent.atomic.AtomicInteger.addAndGet(int delta)
原子性地给当前值增加指定的值,然后返回新值。Atomically adds the given value to the current value.
java.util.concurrent.BlockingQueue<E>
阻塞队列。支持等待以下情形下队列变为非空————当检索一个元素,或当存储元素需要等待可用空间时。
A java.util.Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
boolean java.util.concurrent.LinkedBlockingQueue.offer(E e)
在当前队列的尾部插入指定的元素。
Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity,
java.util.concurrent.SynchronousQueue<E>
一个阻塞队列,它的一个插入操作必须等待来自其他线程的一个对应的移除操作,反之亦然。
A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one.
//: concurrency/AtomicIntegerTest.javaimport java.util.concurrent.* ;import java.util.concurrent.atomic.* ;import java.util.* ;public class AtomicIntegerTest implements Runnable {private AtomicInteger i = new AtomicInteger ( 0 );public int getValue () { return i . get (); }private void evenIncrement () { i . addAndGet ( 2 ); }/* 对比试验,用于替换[7,9]行private int i = 0;public int getValue() { return i; }private synchronized void evenIncrement() { i++;i++; }*/public void run () {while ( true )evenIncrement ();}public static void main ( String [] args ) {//Timer.schedule(TimerTask task, long delay)new Timer (). schedule ( new TimerTask () {public void run () {System . err . println ( "Aborting" );System . exit ( 0 );}}, 5000 ); // Terminate after 5 secondsExecutorService exec = Executors . newCachedThreadPool ();AtomicIntegerTest ait = new AtomicIntegerTest ();exec . execute ( ait );while ( true ) {int val = ait . getValue ();if ( val % 2 != 0 ) {System . out . println ( val );System . exit ( 0 );}}}}/*Aborting*/
来自CODE的代码片
AtomicIntegerTest.java
一个阻塞队列,它的一个插入操作必须等待来自其他线程的一个对应的移除操作,反之亦然。
A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one.