ConcurrentMap 里几个实现为原子性的复合操作

ConcurrentMap接口里封装了一些复合性操作,他们是原子性的操作。

package cn.t1;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class T1 {
	public static void main(String[] args) {
		ConcurrentMap cm=new ConcurrentHashMap();
		
		//不存在key时候,添加成功且返回null,若key已经存在则返回key映射的value
		String pia = cm.putIfAbsent("cs1", "a");
		System.out.println("putIfAbsent:"+pia); //添加成功,返回null
		String pia1 = cm.putIfAbsent("cs1", "a1");
		System.out.println("putIfAbsent:"+pia1); //添加失败,因为key已经存在,此时返回key映射的值a
		System.out.println(cm+"\n");
		
		
		//当存在可以,且key和value映射成功时候才删除返回true
		boolean remove = cm.remove("cs1", "a1");
		System.out.println("remove:"+remove); //key和value没有映射成功,删除失败
		boolean remove1 = cm.remove("cs1", "a");
		System.out.println("remove:"+remove1); //key和value没有映射成功,删除成功
		System.out.println(cm+"\n");
		
		
		//当key存在,且映射到第二个参数上的value时候,才把value替换为第三个参数上的value
		cm.putIfAbsent("cs1", "a");
		boolean replace = cm.replace("cs1", "a1", "b"); //key没有映射到a1上,替换失败返回false
		System.out.println("replace:"+replace);
		System.out.println(cm);
		boolean replace2 = cm.replace("cs1", "a", "b"); //cs1存在,且映射到a上,替换成功返回true
		System.out.println("replace:"+replace2);
		System.out.println(cm);
		
	}

}                                                                                                                                                         
输出:
putIfAbsent:null
putIfAbsent:a
{cs1=a}


remove:false
remove:true
{}


replace:false
{cs1=a}
replace:true
{cs1=b}

你可能感兴趣的:(thread)