需求:
用id来分组,id 相同的分为一组, 同组任务串行执行,不是同组的任务并行。
思路:
需要并行就要使用多线程,但是同组任务需要串行就需要一把锁。用一个list保存正在执行的id, 执行任务前检查是否有相同的id正在执行任务,如果有就休眠等待,没有就继续执行。任务执行完后从list中移除掉,并且唤醒等待的任务。
代码实现 :
1. 对线程的封装
public class Task implements Runnable {
private Long taskName;
private AuthenticTask authenticTask;
public Task(Long name, AuthenticTask authenticTask) {
this.taskName = name;
this.authenticTask = authenticTask;
}
@Override
public void run() {
List<Long> processingTaskNames = ThreadShareData.getProcessingTaskNames();
try {
synchronized (taskName){
//如果任务正在执行等待
if(processingTaskNames.contains(taskName)){
taskName.wait();
}
processingTaskNames.add(taskName);
//开始执行真正的任务
System.out.println(taskName + "开始执行任务.......");
authenticTask.process();
//任务执行完把任务移除
processingTaskNames.remove(taskName);
//唤醒等待的任务
taskName.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2. 辅助类
public interface AuthenticTask {
void process();
}
public class ThreadShareData {
private static List<Long> ProcessingTaskNames = new CopyOnWriteArrayList<Long>();
private static Map<Long, Object> ThreadParamMap = new ConcurrentHashMap<>();
public static List<Long> getProcessingTaskNames() {
return ProcessingTaskNames;
}
public static Map<Long, Object> getThreadParamMap() {
return ThreadParamMap;
}
}
3. 测试
public class ThreadTest {
static ExecutorService pool = Executors.newFixedThreadPool(20);
public static void main(String[] args) throws InterruptedException {
run(1L);
run(2L);
run(1L);
run(1L);
run(1L);
run(2L);
run(2L);
run(1L);
run(3L);
run(2L);
run(3L);
Thread.sleep(35 * 1000);
System.out.println(ThreadShareData.getThreadParamMap());
}
public static void run(final Long threadName) {
pool.execute(new Task(threadName, () -> {
Integer value = (Integer) ThreadShareData.getThreadParamMap().get(threadName);
if (value == null) {
value = 0;
}
ThreadShareData.getThreadParamMap().put(threadName, value + 1);
}));
}
}
4. 运行结果
2开始执行任务.......
1开始执行任务.......
3开始执行任务.......
2开始执行任务.......
1开始执行任务.......
3开始执行任务.......
1开始执行任务.......
2开始执行任务.......
1开始执行任务.......
2开始执行任务.......
1开始执行任务.......
{1=5, 2=4, 3=2}