I have three different synchronized methods show below.
A:
public synchronized static int addCount1() { for (int i = 0; i < 10000; i++) { count++; } return count; } B:
static void addCount2() { synchronized (TestDoubleThread.class) { for (int i = 0; i < 10000; i++) { count++; } } } C:
void addCount3(String key) { synchronized (myMap.get(key)) { for (int i = 0; i < 10000; i++) { count++; } } } All of them can do synchronize as I expect. However, I want to know which one is better, and what is the significant different between all of them. Especially for the case B and case C.
Here is my complete code:
public class TestDoubleThread extends Thread { String jobNmae; static int count = 0; TestDoubleThread(String jobName) { this.jobNmae = jobName; } public static void main(String[] args) throws Exception { TestDoubleThread t1 = new TestDoubleThread("A"); TestDoubleThread t2 = new TestDoubleThread("B"); t1.start(); t2.start(); Thread.sleep(3 * 1000L); System.out.println("count=" + TestDoubleThread.count); } public void run() { // addCount2(); addCount3("A"); } public synchronized static int addCount1() { for (int i = 0; i < 10000; i++) { count++; } return count; } static void addCount2() { synchronized (TestDoubleThread.class) { for (int i = 0; i < 10000; i++) { count++; } } } void addCount3(String key) { synchronized (myMap.get(key)) { for (int i = 0; i < 10000; i++) { count++; } } } public static java.util.Map<String, TestDoubleThread> myMap = new java.util.HashMap<String, TestDoubleThread>(); static { myMap.put("A", new TestDoubleThread("A")); myMap.put("B", new TestDoubleThread("B")); } }
AandBsynchronize on the class itself,Csynchronizes on a lock object that has nothing to do with the static counter that is supposedly being protected. SoCis probably broken.