Skip to content

Instantly share code, notes, and snippets.

@wusisu
Created June 7, 2018 14:02
Show Gist options
  • Save wusisu/82d339db8f556dbb578efd4c7f36a43d to your computer and use it in GitHub Desktop.
Save wusisu/82d339db8f556dbb578efd4c7f36a43d to your computer and use it in GitHub Desktop.
Hashmap Concurrent
import java.util.HashMap;
public class Main {
public static HashMap<String, String> map = new HashMap<>();
public static class Work implements Runnable {
private boolean add;
private long start;
Work(boolean add) {
this.add = add;
}
@Override
public void run() {
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 10 * 1000) {
if (add) {
try {
map.put("1", "2");
} catch (Exception ignored) { }
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
} else {
try {
map.remove("1");
} catch (Exception ignored) { }
try {
Thread.sleep(30);
} catch (InterruptedException ignored) {
}
}
}
}
}
public static void main(String[] args) {
Thread ta = new Thread(new Work(true));
Thread tm1 = new Thread(new Work(false));
Thread tm2 = new Thread(new Work(false));
ta.start();
tm1.start();
tm2.start();
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 10 * 1000) {
System.out.println(map.size());
try {
Thread.sleep(200);
} catch (InterruptedException ignored) {
}
}
System.out.println("Hello world.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment