Java ConcurrentHashMap (Java程式碼實戰-005)

FrankYou發表於2018-05-21

 

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));
            }
        }
    }
}

 

相關文章