背景:模拟创建3000条Json格式的数据用于测试,创建定长线程池,启动10个线程“同时”增加模拟数据,记录生成程序的总时间消耗,最后打印在控制台,或输出到目录文件中
1.创建启动方法,读取服务器目录json文件
import java.io.*;
import java.util.concurrent.ExecutionException;
public class TestData {
private static String data = "";
private static String readText() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("D:\studentFile.txt"));//打开文件创建数据流
String str; //定义String变量用来保存每一次读到的每一行的数据
StringBuffer sb = new StringBuffer();
while ((str = in.readLine()) != null) {
if (str.length() > 0) {
sb.append(str);
}
}
in.close();
data = sb.toString();
return data;
}
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
Long startTime = System.currentTimeMillis();
CallableDemo callableDemo = new CallableDemo();
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(callableDemo.getData());
sb.append("]");
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long ns = 1000;// 一秒钟的毫秒数
//写入文本txt
writeTxt(sb);
Long endTime = System.currentTimeMillis();
Long diff = endTime - startTime;
String result = "0";
// 获得两个时间的毫秒时间差异
long day = diff / nd;// 计算差多少天
long hour = diff % nd / nh + day * 24;// 计算差多少小时
long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
long sec = diff % nd % nh % nm / ns;// 计算差多少秒
System.out.println(diff+"-毫秒");
}
private static void writeTxt(StringBuffer sb) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter("D:\test.txt"));
bw.write(sb.toString());
bw.newline();
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.创建线程任务
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDemo {
public StringBuffer getData() throws IOException, ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
//使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中
// Future future = executorService.submit(new TaskWithResult());
//创建10个任务并执行
List> resultList = new ArrayList>();
for (int i = 0; i < 10; i++) {
//使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中
Future future = executorService.submit(new TaskWithResult());
//将任务执行结果存储到List中
resultList.add(future);
}
//将任务执行结果存储到List中
StringBuffer realtime = new StringBuffer();
//遍历任务的结果
for (Future fs : resultList) {
try {
realtime.append(fs.get());
// System.out.println(fs.get()); //打印各个线程(任务)执行的结果
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
//启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。
executorService.shutdown();
}
}
return realtime;
}
}
3.实现callable接口,执行方法
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; public class TaskWithResult implements Callable{ private StringBuffer sourceData = readText(); private StringBuffer realtime = new StringBuffer(); private static AtomicInteger count = new AtomicInteger(3000); private static AtomicInteger num = new AtomicInteger(0); public TaskWithResult() throws IOException { } @Override public StringBuffer call() throws Exception { System.out.println("call()方法被自动调用,干活!!! " + Thread.currentThread().getName()); Thread.sleep(10); //一个模拟耗时的操作 //业务操作 synchronized (count){ while (count.get() > 0) { if (count.get() == 3000) { realtime.append(sourceData); } else { realtime.append(",").append(sourceData); } System.out.println(Thread.currentThread().getName() + "-当前剩余执行数:" + count.decrementAndGet()); num.incrementAndGet(); } } System.out.println("循环了--" + num); return realtime; } private static StringBuffer readText() throws IOException { BufferedReader in = new BufferedReader(new FileReader("D:\studentFile.txt"));//打开文件创建数据流 String str; //定义String变量用来保存每一次读到的每一行的数据 StringBuffer sb = new StringBuffer(); while ((str = in.readLine()) != null) { if (str.length() > 0) { sb.append(str); } } in.close(); return sb; } }



