并发编程中,需要将一个可能发生线程安全问题的操作变为一个原子操作。方法很多,比如CAS、synchronized、lock。值得一提的是,Java在java.util.concurrent.atomic
下提供了基本类型的包装类型,支持对他们的原子操作。
这里说明一点,多个线程安全的原子操作放到一起并不一定是线程安全的。
比如
class PutValue implements Runnable {
boolean wait;
ConcurrentHashMap<Integer, String> cm;
public PutValue(boolean wait, ConcurrentHashMap<Integer, String> cm) {
// TODO Auto-generated constructor stub
this.wait = wait;
this.cm = cm;
}
@Override
public void run() {
// TODO Auto-generated method stub
Integer key = new Integer(1);
if (!cm.containsKey(key)) {
if (wait)
suspend();
System.out.println(cm.containsKey(key));
cm.put(key, "value");
}
}
// 模拟线程的切换
private void suspend() {
// TODO Auto-generated method stub
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试
public class ConcurrentMapStudy {
public static void main(String[] args) {
ConcurrentHashMap<Integer, String> cm = new ConcurrentHashMap<Integer, String>();
Thread thread1 = new Thread(new PutValue(true, cm));
Thread thread2 = new Thread(new PutValue(false, cm));
thread1.start();
thread2.start();
}
}
结果:false true