Skip to content

Instantly share code, notes, and snippets.

@ofdata
Created March 20, 2015 06:39
Show Gist options
  • Save ofdata/8caf767e07616a2d60f2 to your computer and use it in GitHub Desktop.
Save ofdata/8caf767e07616a2d60f2 to your computer and use it in GitHub Desktop.
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Integer threadNum = 200; // 35
AtomicInteger upCnt = new AtomicInteger(0);
List<MyThreadIcvNew> listThreads = new ArrayList<MyThreadIcvNew>();
Map<String, Map<String, Integer>> countMap = new ConcurrentHashMap<String, Map<String, Integer>>();
for (int i = 0; i < threadNum; i++)
{
MyThreadIcvNew thread = new MyThreadIcvNew(
"Thread" + i, countMap, upCnt);
listThreads.add(thread);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("1", 0);
map.put("2", 0);
countMap.put("Thread" + i, map);
thread.start();
}
for (MyThreadIcvNew t : listThreads)
{
t.join();
}
int cnt1 = 0;
int cnt2 = 0;
for (Map<String, Integer> m : countMap.values())
{
cnt1 = cnt1 + m.get("1");
cnt2 = cnt2 + m.get("2");
}
System.out.println(upCnt.get());
System.out.println(countMap);
System.out.println("cnt1=" + cnt1);
System.out.println("cnt2=" + cnt2);
System.out.println("total=" + (cnt1 + cnt2));
}
static class MyThreadIcvNew extends Thread
{
private Map<String, Map<String, Integer>> countMap;
private AtomicInteger upCnt;
private String threadName;
public MyThreadIcvNew(String threadName, Map<String, Map<String, Integer>> countMap,
AtomicInteger upCnt)
{
super();
this.countMap = countMap;
this.upCnt = upCnt;
this.threadName = threadName;
}
@Override
public void run()
{
System.out.println("线程名称:" + threadName);
for (int i = 0; i < 10000; i++)
{
String key = new Random().nextInt(2) + 1 + "";
countMap.get(threadName).put(key, countMap.get(threadName).get(key) + 1);
upCnt.incrementAndGet();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment