package Threads; import com.google.common.collect.Maps; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by xfyou 2018/5/21 16:55. * 一个采用ConcurrentHashMap并发写数据的例子 */ public class ConcurrentHashMapDemo { private final ConcurrentMap<Integer, String> conHashMap = Maps.newConcurrentMap(); public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(3); try { ConcurrentHashMapDemo ob = new ConcurrentHashMapDemo(); service.execute(ob.new WriteThreadOne()); service.execute(ob.new WriteThreadTwo()); service.execute(ob.new ReadThread()); } finally { service.shutdown(); } } /** * 线程A向Map中put数据 */ class WriteThreadOne implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { conHashMap.putIfAbsent(i, "A" + i); } } } /** * 线程B向Map中put数据 */ class WriteThreadTwo implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { conHashMap.putIfAbsent(i, "B" + i); } } } /** * 线程C读取Map中的数据 */ class ReadThread implements Runnable { @Override public void run() { for (Integer k : conHashMap.keySet()) { System.out.println(k + ":" + conHashMap.get(k)); } } } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/15928.html