1. java创建多线程,异步流程处理
public class startThread implements Runnable {
String day = "";
String from = "";
String end = "";
public startThread(String day, String from, String end) {
this.day = day;
this.from = from;
this.end = end;
}
@Override
public void run() {
try {
} catch (Exception e) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
sout("计算功能异常:\r\n"+sw.toString());
sw.close();
pw.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
new Thread(new startThread(day,from,end)).start();
2. java创建带返回值的多线程
package com.yeahmobi.dsp.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
public class WithReturnThread {
public static void main(String[] args) throws ExecutionException,
InterruptedException {
System.out.println("----程序开始运行----");
Date date1 = new Date();
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
Future f = pool.submit(c);
list.add(f);
}
pool.shutdown();
for (Future f : list) {
System.out.println(">>>" + f.get().toString());
}
Date date2 = new Date();
System.out.println("----程序结束运行----,程序运行时间【"
+ (date2.getTime() - date1.getTime()) + "毫秒】");
}
}
class MyCallable implements Callable<Object> {
private String sql;
private ClickhouseDao clickhouseDao;
public MyCallable(String sql, ClickhouseDao clickhouseDao) {
this.sql = sql;
this.clickhouseDao = clickhouseDao;
}
public MyCallable(String sql) {
this.sql = sql;
}
public Object call() throws Exception {
JSONArray query = clickhouseDao.query(sql.toString());
if (query.size() > 0) {
return query.get(0);
} else {
return new JSONObject();
}
}
}