import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TestThred03 extends Thread { private static int num = 0; private static int num1 = 0; private static HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); public TestThred03() { num = 0; num1=0; hashMap.put("1", 0); hashMap.put("2", 0); hashMap.put("3", 0); hashMap.put("4", 0); hashMap.put("5", 0); } public void run() { Iterator iter = hashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); if (key.equals("1") || key.equals("2")) { synchronized (this) { num++; entry.setValue(num); System.out.println(Thread.currentThread().getName()+"-num:"+num); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } else { synchronized (this) { num1++; entry.setValue(num1); System.out.println(Thread.currentThread().getName()+"-num1:"+num1); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { TestThred03 syncThread = new TestThred03(); Thread thread1 = new Thread(syncThread, "SyncThread1"); Thread thread2 = new Thread(syncThread, "SyncThread2"); thread1.start(); thread2.start(); } }