Updating and Iterating a Map - Java Thread

Java examples for Thread:Concurrent Map

Description

Updating and Iterating a Map

Demo Code

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class Main {
  Random random = new Random();
  Set<Thread> updateThreads = new HashSet<>();

  public static void main(String[] args) {
    Main recipe = new Main();
    recipe.startProcess();//from www.ja v  a  2 s.  c  om
  }
  private void startProcess() {
    ConcurrentMap<Integer, String> concurrentMap = new ConcurrentHashMap<>();
    for (int i = 0; i < 1000; i++) {
      startUpdateThread(i, concurrentMap);
    }
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    concurrentMap
        .entrySet()
        .stream()
        .forEach(
            (entry) -> {
              System.out.println("Key :" + entry.getKey() + " Value:"
                  + entry.getValue());
            });
    updateThreads.stream().forEach((thread) -> {
      thread.interrupt();
    });
  }
  private void startUpdateThread(int i,
      final ConcurrentMap<Integer, String> concurrentMap) {
    Thread thread = new Thread(() -> {
      while (!Thread.interrupted()) {
        int randomInt = random.nextInt(20);
        concurrentMap.put(randomInt, UUID.randomUUID().toString());
      }
    });
    thread.setName("Update Thread " + i);
    updateThreads.add(thread);
    thread.start();
  }
}

Result


Related Tutorials