50,499
社区成员
发帖
与我相关
我的任务
分享
package com.demo;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class thread01 {
Map<Integer, Integer> controlMap = Collections.synchronizedMap(new HashMap<Integer, Integer>());
public static void main(String[] args) {
System.out.println("hh");
new thread01().TestDemo();
}
public void TestDemo() {
for (Integer i = 0; i < 10; i++) //初始化状态
{
controlMap.put(i, 0);
Thread t1 = new Thread(new subThread(i));
t1.start();
}
Integer complateCount = 0;
while (complateCount < 10) {
try {
Thread.sleep(1000 * 1);//等待1s看结果
complateCount = 0;
for (Integer i = 0; i < 10; i++) {
if (controlMap.get(i) == 100) {
complateCount++;
}
}
System.out.println("完成线程的个数是:" + complateCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class subThread implements Runnable {
private Integer threadControlId;
public subThread(Integer id) {
threadControlId = id;
}
public void run() {
for (Integer i = 1; i <= 10; i++)//线程内模拟耗时任务
{
try {
Thread.sleep((long) (1000 * (i * Math.random())));
controlMap.put(threadControlId, i * 10);//100代表完成
System.out.println("线程" + threadControlId + "完成" + i * 10 + "%");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}