没什么难度,简单记录一下,主要避免线程安全问题就行
1.背景
定时任务拉取加密数据,解密后入库
2.实现
java代码哦
package com.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
public class ExecTest {
public static void main(String[] args) throws InterruptedException {
//多线程和单线程处理结果进行对比,检查数据正确性
System.out.println(test2().toString().equals(decrytData().toString()));
}
/**
* 多线程处理
*/
public static List<String> decrytData() throws InterruptedException {
long start = System.currentTimeMillis();
ExecutorService executorService = new ThreadPoolExecutor(5, 10,1,
TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000, true),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
// 造数据
List<String> data = new ArrayList<>(900);
for(int i=1;i<801;i++) {
if (i < 201) {
data.add("a"+i);
}else if (i < 401) {
data.add("b"+i);
}
else if (i< 601) {
data.add("c"+i);
}
else {
data.add("d"+i);
}
}
/*List<String> result = new CopyOnWriteArrayList<>();*/
/*List<String> result = new ArrayList<>();*/
List<String> result = Collections.synchronizedList(new ArrayList<>(900));
for (int i=0;i<8;i++) {
System.out.println(i);
List<String> strings = data.subList(i*100, (i + 1) * 100);
executorService.execute(() -> {
try {
List<String> test = test(strings);
result.addAll(test);
System.out.println(result);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
Collections.sort(result);
System.out.println(result);
System.out.println("size"+result.size());
System.out.println(System.currentTimeMillis() - start);
return result;
}
/**
* 单线程处理
*/
public static List<String> test2() throws InterruptedException {
long start = System.currentTimeMillis();
List<String> data = new ArrayList<>(900);
for(int i=1;i<801;i++) {
if (i < 201) {
data.add("a"+i);
}else if (i < 401) {
data.add("b"+i);
}
else if (i< 601) {
data.add("c"+i);
}
else {
data.add("d"+i);
}
}
List<String> test = test(data);
Collections.sort(test);
System.out.println(test);
System.out.println(test.size());
System.out.println(System.currentTimeMillis() - start);
return test;
}
/**
* 这是个数据解密方法,你可以当成RSA解密
*/
public static List<String> test(List<String> a) throws InterruptedException {
List<String> newList = new ArrayList<>(900);
for (String aa:a) {
aa = aa + "!";
newList.add(aa);
// 延时,伪装成解密的样子
Thread.sleep(5);
}
return newList;
}
}
List<String> result要注意线程安全问题。
这里,多线程执行完,结果需要每一个线程处理的结果的集合,所以通过
executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
这段代码等待线程结束。