Java 多线程 ConcurrentHashMap

Java 多线程 ConcurrentHashMap

package thread.map;

import java.util.concurrent.ConcurrentHashMap;

public class Consumer implements Runnable {
  private String name;
  private ConcurrentHashMap<String, String> map;
  private int fromIndex;

  public Consumer(String name, ConcurrentHashMap<String, String> map, int fromIndex) {
    this.name = name;
    this.map = map;
    this.fromIndex = fromIndex;
  }

  public void run() {
    for (int i = fromIndex; i < fromIndex + 20; i++) {
      String str = String.valueOf(i);
      map.remove(str);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println(name + ", remove. size:" + map.size());
  }
}
package thread.map;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class View implements Runnable {
  private String name;
  private ConcurrentHashMap<String, String> map;

  public View(String name, ConcurrentHashMap<String, String> map) {
    this.name = name;
    this.map = map;
  }

  public void run() {
    Iterator<String> iter = map.values().iterator();
    while (iter.hasNext()) {
      String str = iter.next();
      System.out.println(name + ", " + str);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
package thread.map;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
  /**
   * @author jzh add 2012-01-07
   * @param args
   */
  public static void main(String[] args) {
    // 初始ConcurrentHashMap
    ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
    for (int i = 0; i < 100; i++) {
      String str = String.valueOf(i);
      map.put(str, str);
        }
    
    // 创建一个线程池(创建一个可根据需要创建新线程的线程池)
    // Executors 类提供了用于此包中所提供的执行程序服务的工厂方法
    ExecutorService pool = Executors.newCachedThreadPool();
    
    Consumer consumer0 = new Consumer("howsky0", map, 10);
    Consumer consumer1 = new Consumer("howsky1", map, 40);
    Consumer consumer2 = new Consumer("howsky2", map, 70);
    View view = new View("jiang", map);

    pool.execute(consumer0);
    pool.execute(consumer1);
    pool.execute(consumer2);
    pool.execute(view);
    
    pool.shutdown();

  }
}

 

发表回复

您的电子邮箱地址不会被公开。