class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
class Resource {
// ...
public void doSomething() {
// ...
}
public void doAnotherThing() {
// ...
}
}
class MyThread implements Runnable {
private Resource resourceA;
private Resource resourceB;
public MyThread(Resource resourceA, Resource resourceB) {
this.resourceA = resourceA;
this.resourceB = resourceB;
}
public void run() {
synchronized (resourceA) {
resourceA.doSomething();
synchronized (resourceB) {
resourceB.doAnotherThing();
}
}
}
}
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
executor.execute(new MyRunnable());
}
executor.shutdown();
ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}