原子类 与 volatile

volatile

如果你将一个域声明为volatile的,那么只要对这个域产生了写操作,它就会被立即写入到内存中。
若不用volatile关键字,这个域就只能用同步来访问,因为同步也会向主存刷新。

Atomic

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.java
import 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 seconds
ExecutorService 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

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值